Can a static method access a non-static instance variable?

So, I realized that you cannot use the static method to access non-stationary variables, but I came across the 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 don't

public static void repair(Laptop laptop) {
laptop.memory = "2GB";
}

access to string memory defined in the Notebook class, which is a non-static instance variable?

Since the code compiles without any error, I assume that I do not understand anything. Can someone please tell me what I do not understand?

+4
source share
2 answers

, . - , , .

, , :

class Test {
  int x;

  public static doSthStatically() {
    x = 0; //doesn't work!
  }
}

, Test . , , , x this.x ( this), this .

, x.

:

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
  }
}
+12

object reference.

, , , . , .

+1

All Articles