So my understanding was that you can't use static method to access non-static variables, but I came across following code.
class Laptop {
String memory = "1GB";
}
class Workshop {
public static void main(String args[]) {
Laptop life = new Laptop();
repair(life);
System.out.println(life.memory);
}
public static void repair(Laptop laptop) {
laptop.memory = "2GB";
}
}
Which compiles without errors.
So isn't
public static void repair(Laptop laptop) {
laptop.memory = "2GB";
}
accessing String memory defined in class Laptop, which is non-static instance variable?
Since the code compiles without any error, I'm assuming I'm not understanding something here. Can someone please tell me what I'm not understanding?
Static methods cannot access or change the values of instance variables or the this reference (since there is no calling object for them), and static methods cannot call non-static methods.
Of course, they can, but the opposite is not true, i.e. you cannot obtain a non-static member from a static context, i.e. static method. The only way to access a non-static variable from a static method is by creating an object of the class the variable belongs to.
Static member functions are allowed to access only the static data members or other static member functions, they can not access the non-static data members or member functions of the class.
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
}
}
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