Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does non-static method access static members in java?

Consider this:

class SomeClass
{
   static int a;
   int method()
   {
      int b = a;
      return b;
   }
}

How does a is being accessed in method? Is it this.a or someClass.a?

EDIT: Sorry if I'm not clear in my question. What I want to know is: *Is there a hidden this or someClass associated with a [in method] or is it simply a [in method] that is accessing the class member?

like image 210
Alvin3001 Avatar asked Feb 19 '26 18:02

Alvin3001


2 Answers

It's just a: the same field for any instance of the class. You can write someClass.a if you need an explicit disambiguation.

Consider carefully why you would want a non-static method that returns a static member though: it seems like a code "smell" to me.

like image 107
Bathsheba Avatar answered Feb 21 '26 07:02

Bathsheba


I will edit your example in order to make it look a little bit more right:

public class SomeClass
{
   private static int a = 1;
   public int method()
   {
      int b = a;
      return b;
   }
}

int b = a; is equal to int b = SomeClass.a;

Don't be confused with this - it is a reference to an object. Static fields belong to a class, not to an object, so it is incorrect to get a with this.a

And, as already mentioned here:

Instance methods can access class variables and class methods directly.

like image 32
hammelion Avatar answered Feb 21 '26 07:02

hammelion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!