Reputation: 2983
I'm preparing the OCA certification for Java SE 7 and during the first chapter Java Basics, I read the following things about static methods:
Static methods aren't associated with objects and can't use any of the instance variable of a class.
In the following example the compiler gives me an error:
class MyClass2 {
String a;
public MyClass2() {
}
static void check(){
if (a.equals("TEST"))
return;
}
}
Cannot make a static reference to the non-static field a.
If I change the class definition in this way:
class MyClass {
String a;
public MyClass() {
// TODO Auto-generated constructor stub
check(a);
}
static void check(String a){
if (a.equals("TEST"))
return;
}
}
everything works and the compiler doesn't show any error, which is strange because a
is always an instance variable.
Upvotes: 3
Views: 7589
Reputation: 7
When you pass an instance variable to a static method (or any other method for that matter) you pass the value of that variable. Not the variable itself. That's probably why you are not getting error. The variable itself however, doesn't become available.
Upvotes: 0
Reputation: 876
A static method can only refer to static variables. As non static variables do not belong to the class, but to specific objects that are instantiated... there is no way for a static method to know which of the variables to show. For example you create two instances of MyClass
MyClass x,y;
x.a =10;
x.b=20;
Then there is no way to know which one is right one to pick from static function as Static function is not associated with any specific instance (x or y).
So in case you want to access variable a you need to declare it as static.
static String a;
BUT, in your second case you have a as parameter, so as the parameter is being referred in place of the class level variable there is no error. In case you want error use this.a to refer to class level variable.
Upvotes: 1
Reputation: 11163
In first case while compilation error occurred -
String a
String a
from you static method check()
That's why the compilation error occurred
And in second case while no compilation error occurred -
check()
from your constructor MyClass()
. Hope it will help you.
Thanks a lot.
Upvotes: 0
Reputation: 311338
In the second example, you check
has a parameter called a
. The equality check is performed against it, and not against the instance member a
which is, indeed, still inaccessible from a static
context.
Upvotes: 2