luke luke - 5 months ago 3x
Java Question

How to access variables of a method in a different class in Java?

I have some variables in GUI class inside GUI method. How can I access the variables from a different class?


In Java, variables declared inside a method have a scope limited to the method : they are not accessible outside of the method, even in the same class.

In that case, if you want to access them from outside, this means that their place is probably not as variables of the method, but as members of the class, ie "variables" declared as properties of the class, like this :

class Example {

   public int field; 


If you are referring to members, then whether you can access this field from outside the class depends on what you write in front of the field declaration :

  • public : field will be accessible outside of the class
  • protected : field will be accessible only in classes that extend this class
  • private : field will be accessible only inside that class