Can static method access non-static instance variable?
A static method can access non-static methods and fields of any instance it knows of. However, it cannot access anything non-static if it doesn't know which instance to operate on.
I think you're mistaking by examples like this that don't work:
class Test {
int x;
public static doSthStatically() {
x = 0; //doesn't work!
}
}
Here the static method doesn't know which instance of Test
it should access. In contrast, if it were a non-static method it would know that x
refers to this.x
(the this
is implicit here) but this
doesn't exist in a static context.
If, however, you provide access to an instance even a static method can access x
.
Example:
class Test {
int x;
static Test globalInstance = new Test();
public static doSthStatically( Test paramInstance ) {
paramInstance.x = 0; //a specific instance to Test is passed as a parameter
globalInstance.x = 0; //globalInstance is a static reference to a specific instance of Test
Test localInstance = new Test();
localInstance.x = 0; //a specific local instance is used
}
}