[java] How do I get some variable from another class in Java?

I am "playing around" with Java, watching tutorials and trying to get the hang of it. For this question, I'm trying to figure out how I can take a variable from another class and use it in my main one, without making the initial variable public. Here is the code:

I am trying to get int x equal to 5 (as seen in the setNum() method), but when it prints it gives me 0.

Main Class:

package getVarTest;  public class Main {      public static void main (String[]args){         Vars varsObject = new Vars();         int x = varsObject.getNum();         System.out.println(x);     } } 

Variable Class:

package getVarTest;      public class Vars {         private int num;             public void setNum(int x){                 this.num = 5;             }             public int getNum(){                 return num;             }     } 

So, as you can see I am trying to take the private int num and make the int x in the main class equal to it.

This question is related to java

The answer is


I am trying to get int x equal to 5 (as seen in the setNum() method) but when it prints it gives me 0.

To run the code in setNum you have to call it. If you don't call it, the default value is 0.


You never call varsObject.setNum();


Your example is perfect: the field is private and it has a getter. This is the normal way to access a field. If you need a direct access to an object field, use reflection. Using reflection to get a field's value is a hack and should be used in extreme cases such as using a library whose code you cannot change.


The code that you have is correct. To get a variable from another class you need to create an instance of the class if the variable is not static, and just call the explicit method to get access to that variable. If you put get and set method like the above is the same of declaring that variable public.

Put the method setNum private and inside the getNum assign the value that you want, you will have "get" access to the variable in that case