Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...