luke luke - 1 year ago 57
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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download