Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get Variables values from other class in java to 2 different class

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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());
}
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading