所以我的理解是你不能使用静态方法来访问非静态变量,但我遇到了以下代码。
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";
}
}
编译没有错误。
不是吗
public static void repair(Laptop laptop) {
laptop.memory = "2GB";
}
访问类 Laptop 中定义的 String 内存,它是非静态实例变量?
由于代码编译没有任何错误,我假设我不理解这里的某些东西。有人可以告诉我我不明白的地方吗?
最佳答案
静态方法可以访问它知道的任何实例的非静态方法和字段。但是,如果它不知道要操作哪个实例,它就无法访问任何非静态内容。
我认为你误以为这样的例子不起作用:
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
}
}
关于java - 静态方法可以访问非静态实例变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38263533/