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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With