所以我的理解是你不能使用静态方法来访问非静态变量,但我遇到了以下代码。
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";
}
访问笔记本电脑类中定义的字符串内存,这是非静态实例变量?
由于代码编译没有任何错误,我假设我在这里不理解某些东西。有人可以告诉我我不明白的地方吗?
原文由 SERich 发布,翻译遵循 CC BY-SA 4.0 许可协议
静态方法可以访问它知道的任何实例的非静态方法和字段。但是,如果它不知道要操作哪个实例,它就无法访问任何非静态的东西。
我认为你误以为这样的例子不起作用:
这里静态方法不知道它应该访问哪个实例
Test
。 In contrast, if it were a non-static method it would know thatx
refers tothis.x
(thethis
is implicit here) butthis
在静态上下文中不存在。但是,如果您提供对实例的访问,即使是静态方法也可以访问
x
。例子: