i want to ask about Object Oriented Programming stuff.
so i got 3 classes, ( Main Class, Second Class, Third Class ) on same Package.
Main.class
public static void main(String[] args) {
int var_main = 0;
Scanner input = new Scanner(System.in);
Second second = new Second();
System.out.print("Input some number to save : ");
var_main = input.nextInt();
second.setCount(var_main);
new Third();
}
Second.class
public class Second {
private int count;
public void setCount(int count) {
this.count = count;
}
public int getCount() {
return this.count;
}
}
Third Class
public class Third {
public Third() {
Second second = new Second();
System.out.println("Number Saved from Main Class : "+second.getCount());
}
}
The output from the Third.class is 0 why it’s not values from the Main class ? i still confused with this, thank you very much.
>Solution :
As others mentioned in the comment, you are creating the brand new Second object inside the Third class constructor.
I modified your code and added the comments so you can understand what others commented on your question.
Main
public static void main(String[] args) {
int var_main = 0;
Scanner input = new Scanner(System.in);
Second second = new Second();
System.out.print("Input some number to save : ");
var_main = input.nextInt();
second.setCount(var_main);
//pass the second object which you updated the count in order to print the count inside Third Constructor.
new Third(second);
}
Second class
public class Second {
private int count;
public void setCount(int count) {
this.count = count;
}
public int getCount() {
return this.count;
}
}
Third Class
public class Third {
public Third(Second second) { //Now you need to pass the second reference to this Third class constructor to print the result you expecting..
// You are creating new Second object and whatever you set the count in main class is different and this one is different..
//Second second = new Second();
System.out.println("Number Saved from Main Class : "+second.getCount());
}
}