How to Print another classes information in different package + class - java

I have these 2 classes in each of its own packages too
package app;
import data.Sukka;
public class Kauppa {
public static void main(String[] args) {
Sukka sukka=new Sukka();
sukka.setId(1);
sukka.setKoko(22);
sukka.setVari("musta");
sukka.setMateriaali("kangas");
sukka.setHinta("20eur");
tulostaSukka(sukka);
}
private static void tulostaSukka(Sukka sukka)
{ // TODO Auto-generated method stub
System.out.println("Sukan id:"+sukka.getId());
System.out.println("Sukan koko:"+sukka.getKoko());
System.out.println("Sukan väri:"+sukka.getVari());
System.out.println("Sukan materiaali:"+sukka.getMateriaali());
System.out.println("Sukan hinta:"+sukka.getHinta());
}
}
package data;
public class Sukka {
private int id;
private String vari;
private int koko;
private String materiaali;
private String hinta;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getVari() {
return vari;
}
public void setVari(String vari) {
this.vari = vari;
}
public int getKoko() {
return koko;
}
public void setKoko(int koko) {
this.koko = koko;
}
public String getMateriaali() {
return materiaali;
}
public void setMateriaali(String materiaali) {
this.materiaali = materiaali;
}
public String getHinta() {
return hinta;
}
public void setHinta(String hinta) {
this.hinta = hinta;
}
}
This is made so it shows the list of koko, väri etc etc.
I should create 3class in new package which would just print the attribute of sukka at once and so you would be able to choose which attribute you want it to print.

If you want to see the various fields you just need to get the Class object from the class as follows
Class c = Sukko.getClass()
c.getFields()
And then if you want to give the user the option to select which field should be displayed you will have to look at the reflections API

Related

how to create a List type of non public class from another package?

My Package A has one java file with 2 classes. Login class which is public and LoginDetails class which cannot be public because it is in the same file. how to create a List of LoginDetails type from Package B.
package A;
public class Login {
private String name;
private String passWord;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
#Override
public String toString() {
return "Login [name=" + name + ", passWord=" + passWord + "]";
}
}
class LoginDetails{
public LoginDetails(int id, int geight) {
super();
this.id = id;
this.geight = geight;
}
private int id;
private int geight;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getGeight() {
return geight;
}
public void setGeight(int geight) {
this.geight = geight;
}
public void hidden() {
System.out.println("From hidden");
}
public LoginDetails() {
}
}
package B;
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
List<LoginDetails> l = new ArrayList<LoginDetails>();
}
}
A solution to your weird question which doesnt include changing neither of the Login nor LoginDetails classes would be by adding a second Public class called AUtils such like this:
AUtils/AFactory class
package A;
import java.util.ArrayList;
public class AUtils {
public static ArrayList<LoginDetails> generateList(){
return new ArrayList<LoginDetails>();
}
public static ArrayList<LoginDetails> generateListWithInitialSize(int x){
return new ArrayList<LoginDetails>(x);
}
public static LoginDetails generateAnObject(){
return new LoginDetails();
}
public static LoginDetails generateWithData(int id, int geight){
return new LoginDetails(id,geight);
}
}
And your Demo would look like this:
public class Demo {
public static void main(String[] args) {//plus you dont need To throw exception thus your program dont throw any!:)
List l = AUtils.generateList();
// List l = AUtils.generateListWithInitialSize(10);//will give you array list with initial size 10
l.add(AUtils.generateAnObject());//if you do so be aware that the objects would be created with 0 as id and eight.
// l.add(AUtils.generateWithData(3,3));
}
}
please be aware that this normally is not acceptable and considered as bad coding because its kinda turn around ;) so either you misunderstood the assignment or the one who wrote it is really a carrot.
happy coding.
You cannot do it directly without changing of the design or visibility of the classes.
If a class has no modifier (the default, also known as
package-private), it is visible only within its own package.
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

How to change the value of private variable in java

I started to programm in Java since Yesterday, and I have the biggest question of my entire programmer life(since Yesterday).
For example, let's say I have a code like this:
public class itsAClass {
static private String A;
public static void main() {
A = "This should be changed";
}
public String something() {
return A;
}
}
I wanted to use the method something() in another Class to get the String Sentence of A, but I got only null.
How can I change the value of A, so that the another Class can get the Value "This should be changed"?
If you just want to bring this code to work you just can make something() static as well.
But this will be not the right way to approach this problem.
If you want to hold code in the main class you could do something like this:
public class AClass {
private String a;
public static void main() {
AClass myC = new AClass();
myC.setA("This should be changed");
// than use myC for your further access
}
public String something() {
return a;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
}
If you want to access it by a external class without direct reference you can checkout the singleton pattern.
public class AClass {
private final static AClass INSTANCE = new AClass();
private String a;
public static void main() {
getSingleton().setA("This should be changed");
}
public String something() {
return a;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public static AClass getSingleton() {
return INSTANCE;
}
}
This way you can access it via AClass.getSingleton() from any location of your code.
You have to call your main() function.
In another class:
itsAClass aClassObj = new itsAClass();
aClassObj.main();
// or rather itsAClass.main() as it is a static function
// now A's value changed
System.out.println(aClassObj.something());
the way to set the value of private variable is by setter and getter methods in class.
example below
public class Test {
private String name;
private String idNum;
private int age;
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getIdNum() {
return idNum;
}
public void setAge( int newAge) {
age = newAge;
}
public void setName(String newName) {
name = newName;
}
public void setIdNum( String newId) {
idNum = newId;
}
}
you can call method main() in method something().
public class itsAClass{
static private String A;
public static void main() {
A = "This should be changed";
}
public String something() {
main();
return A;
}
public static void main(String[] args){
itsAClass a1 = new itsAClass();
System.out.println(a1.something());// prints This should be changed
}
}

Extending abstract classes

MyMath's constructor is supposed to call Homework's constructor, but super(); returns an error 'cannot find symbol'. It should not have any arguments.
Also, I am confused about how to call the method createAssignment using an arraylist, but I have to use it. Any advice?
Homework
public abstract class Homework {
private int pagesToRead;
private String typeHomework;
public Homework(int pages, String hw) {
// initialise instance variables
pagesToRead = 0;
typeHomework = "none";
}
public abstract void createAssignment(int p);
public int getPages() {
return pagesToRead;
}
public void setPagesToRead(int p) {
pagesToRead = p;
}
public String getTypeHomework() {
return typeHomework;
}
public void setTypeHomework(String hw) {
typeHomework = hw;
}
}
MyMath
public class MyMath extends Homework {
private int pagesRead;
private String typeHomework;
public MyMath() {
super();
}
public void createAssignment(int p) {
setTypeHomework("Math");
setPagesToRead(p);
}
public String toString() {
return typeHomework + " - " + pagesRead;
}
}
public class testHomework {
public static void main(String[] args) {
ArrayList<Homework> list = new ArrayList<Homework>();
list.add(new MyMath(1));
list.add(new MyJava(1));
for (Homework s : list) {
s.createAssignment();
}
}
}
Compiler error:
Regarding the compiler error, you have to change the MyMath constractor to somthing like:
public MyMath() {
super(someInt, someString);
}
Or, you can add a non-arg constructor to the Homework class:
public Homework() {
this(someInt,someString);
}
You can learn about the super() keyword in the Javadocs tutoriel:
If a constructor does not explicitly invoke a superclass constructor,
the Java compiler automatically inserts a call to the no-argument
constructor of the superclass. If the super class does not have a
no-argument constructor, you will get a compile-time error. Object
does have such a constructor, so if Object is the only superclass,
there is no problem.
Code Suggestion:
As there is many other issues in your question, i modified all your classes like below:
Homework.java:
public abstract class Homework {
private int pagesToRead;
private String typeHomework;
{
// initialise instance variables
pagesToRead = 0;
typeHomework = "none";
}
public Homework(int pages, String hw) {
this.pagesToRead = pages;
this.typeHomework = hw;
}
public abstract void createAssignment(int p);
public int getPages() {
return pagesToRead;
}
public void setPagesToRead(int p) {
pagesToRead = p;
}
public String getTypeHomework() {
return typeHomework;
}
public void setTypeHomework(String hw) {
typeHomework = hw;
}
}
MyMath.java
public class MyMath extends Homework {
private int pagesRead;
private String typeHomework;
public MyMath(int pages, String hw) {
super(pages,hw);
}
public void createAssignment(int p) {
setTypeHomework("Math");
setPagesToRead(p);
}
public String toString() {
return typeHomework + " - " + pagesRead;
}
}
TestHomework.java:
class TestHomework {
public static void main(String[] args) {
ArrayList<Homework> list = new ArrayList<Homework>();
// will create a homework with type Math and one page to read
list.add(new MyMath(1,"Math"));
// Assuming MyJava is similar to MyMath
list.add(new MyJava(1,"Java"));
for (Homework s : list) {
if (s instanceof MyMath) {
// modify the number of pages to read for the Math homework
s.createAssignment(3);
} else if (s instanceof MyJava) {
// modify the number of pages to read for the Java homework
s.createAssignment(5);
} else {
s.createAssignment(7);
}
}
}
}

Creating parcelable class

my class looks like this when I run my application and navigate throug the different fragments sometimes it crashes and logcat says that error is BadParcelableException: Parcelable protocol requires a Parcelable.Creator object called CREATOR on class ge.mobility.weather.entity.City
here is my code
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
public class City implements Parcelable {
private String code;
private String name;
private List<CityWeather> weathers ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public List<CityWeather> getWeathers() {
if(weathers == null) {
weathers = new ArrayList<CityWeather>();
}
return weathers;
}
public void addCityWeather(CityWeather w) {
getWeathers().add(w);
}
public void addCityWeathers(List<CityWeather> w) {
getWeathers().addAll(w);
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {enter code here
// TODO Auto-generated method stub`enter code here`
}
}
You need to implement the Parcelable.Creator and also add the un/serialise methods and a constructor:
public City(Parcel in) {
readFromParcel(in);
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(code);
dest.writeString(name);
dest.writeTypedList(weathers);
}
private void readFromParcel(Parcel in) {
code = in.readString();
name = in.readString();
in.readTypedList(weathers, CityWeather.CREATOR);
}
public static final Parcelable.Creator<City> CREATOR = new Parcelable.Creator<City>() {
public City createFromParcel(Parcel in) {
return new City(in);
}
public City[] newArray(int size) {
return new City[size];
}
};
You will also need to implement the Parcelable methods for the CityWeather class.
Try this code generation library Parceler , if you are use InteliJ Use this plugin IntelliJ Plugin for Android Parcelable boilerplate code generation

Passing a variable from parent to child class in Java

I am completely new to Java... :(
I need to pass a variable from a parent class to a child class, but I don't know how to do that.
The variable is located in a method in the parent class and I want to use it in one of the methods of the child class.
How is this done?
public class CSVData {
private static final String FILE_PATH="D:\\eclipse\\250.csv";
#Test
public static void main() throws IOException {
//some code here
String firstname1 = array.get(2).get(1);
}
}
and then the other class
public class UserClassExperimental3 extends CSVData {
public static void userSignup() throws InterruptedException {
//some code here
String firstname= firstname1; //and here it doesnt work
}
}
Actually I think I succeeded doing that this way:
added the variable here:
public static void userSignup(String firstname1)
then used it here:
String firstname=firstname1;
System.out.println(firstname);
But now I can't pass it to the method that needs it.
The variable firstname1 is a local variable. You can't access it outside its scope - the method.
What you can do is pass a copy of the reference to your subclass.
Since you're calling a static method, the easiest way is to pass the reference as an argument to the method call:
#Test
public static void main() throws IOException {
//some code here
String firstname1 = array.get(2).get(1);
UserClassExperimental3.userSignup( firstName1 );
}
public class UserClassExperimental3 extends CSVData {
public static void userSignup( String firstNameArg ) throws InterruptedException {
//some code here
String firstname = firstnameArg; // Now it works
}
}
That said, since you're using inheritance, you might find it useful to use an instance method. Remove "static" from the method. In main(), construct an instance of the class, provide it the name, and call the method on the instance.
#Test
public static void main() throws IOException {
//some code here
String firstname1 = array.get(2).get(1);
UserClassExperimental3 instance = new UserClassExperimental3( firstName1 );
instance.userSignup();
}
public class UserClassExperimental3 extends CSVData {
private String m_firstName;
public UserClassExperimental3( String firstName ) {
m_firstName = firstName;
}
public void userSignup() throws InterruptedException {
//some code here
String firstname = m_firstname; // Now it works
}
}
If you also add userSignup() to the CSVData class, you can refer to the specific subclass only on creation. This makes it easier to switch the implementation, and it makes it easier to write code that works regardless of which subclass you're using.
String firstname1 = array.get(2).get(1);
CSVData instance = new UserClassExperimental3( firstName1 );
instance.userSignup();
public class Main {
public static void main(String[] args) {
User user=new User();
user.setId(1);
user.setName("user");
user.setEmail("user#email.com");
user.save();
}
}
public class User extends Model {
private int id;
private String name;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
import java.lang.reflect.Field;
public class Model {
public void save(){
for(Field field: Model.this.getClass().getDeclaredFields()) {
field.setAccessible(true);
try {
System.out.println(field.getName()+"="+field.get(Model.this));
} catch (Exception ex) {
ex.printStackTrace();
}
}
return;
}
}

Categories

Resources