Can static method access non-static instance variable?

后端 未结 5 2238
天命终不由人
天命终不由人 2020-12-16 19:31

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 =          


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-16 19:55

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

提交回复
热议问题