Reputation: 277
In Java when we want to access a non-static variable from a static method, we get a compile error:
"Cannot make a static reference to the non-static field nonStatic"
But I made the other class with a static method, and I could reach that non-static variable. Why is this?
So in class A, the line "return nonStatic" and the line "nonStatic=4" is bad. But in the class App method m, and the class B method m is working.
public class App
{
public static void main( String[] args )
{
A a = new A();
m( a );
System.out.println(a.nonStatic);
}
static void m( A a ) {
a.nonStatic = 12; //its good...why?
}
}
class A{
int nonStatic = 7;
static int getOrSetNonStatic(){
// return nonStatic; //error
// nonStatic = 4; //error
return 0;
}
}
class B {
static void m( A a ) {
a.nonStatic = 12; //its good...why?
}
}
Upvotes: 1
Views: 135
Reputation: 45309
What makes the difference is not the fact that nonStatic
is accessed from a different class.
Try doing that in A and it will compile:
class A {
int nonStatic = 7;
static void m( A a ) {
a.nonStatic = 12;
}
}
So what makes the difference? It's what you read the static variable on:
a.nonStatic
accesses nonStatic
on an instance. Regardless of where this code is, it is OK.nonStatic
in an instance (non-static) method inside A
is similar to a.nonStatic
(i.e., this.nonStatic
). This is allowed.nonStatic
in a static method inside A
is equivalent to A.nonStatic
, which is a problem regardless of where it's written. nonStatic
is an instance field, so it cannot be accessed statically (as A.nonStatic
anywhere, or as nonStatic
in a static method of A
)Upvotes: 2
Reputation: 96385
Because you passed it into the method as an argument.
Maybe it would be clearer if you gave the method parameter a different name. Then you would see that the member field wasn’t visible as a but only under the parameter name.
Upvotes: 2