Reputation: 109
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?
Upvotes: 3
Views: 1338
Reputation: 351
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.
Upvotes: 1
Reputation: 518
As long as the static member is public, you can use "SomeClass.a" from any class. For private members, create an accessor method if you really need to access the member and from within the class, just specify it as "a".
Upvotes: 0
Reputation: 234715
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.
Upvotes: 2
Reputation: 505
If you're inside the class you can access it by just calling a
From any other class you'll receive this static member by using someClass.a
Upvotes: 0