Can static method access non-static instance variable?

后端 未结 5 2205
天命终不由人
天命终不由人 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:47

    You can access only with object reference.

    Instance variables defined at class level, have to be qualified with object name if you are using in a static context. But it does not not mean that you cannot access at all.

    0 讨论(0)
  • 2020-12-16 19:47

    try this code

    public static void repair() {
    
        Laptop laptop =new Laptop();
    
        laptop.memory="2GB";
    
      }
    
    0 讨论(0)
  • 2020-12-16 19:49

    Yes, a non-static method can access a static variable or call a static method in Java. There is no problem with that because of static members

    i.e. both static variable and static methods belongs to a class and can be called from anywhere, depending upon their access modifier.

    For example, if a static variable is private then it can only be accessed from the class itself, but you can access a public static variable from anywhere.

    Similarly, a private static method can be called from a non-static method of the same class but a public static method e.g. main() can be called from anywhere

    0 讨论(0)
  • 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
      }
    }
    
    0 讨论(0)
  • 2020-12-16 20:04

    Static methods cannot modify their value. You can get their current value by accessing them with the reference of current class.

    0 讨论(0)
提交回复
热议问题