问题描述
所以我的理解是您不能使用静态方法来访问非静态变量,但是我遇到了以下代码.
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";
}
}
哪个编译没有错误.
不是
public static void repair(Laptop laptop) {
laptop.memory = "2GB";
}
访问类Laptop中定义的字符串内存,这是非静态实例变量吗?
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?
推荐答案
静态方法可以访问其知道的任何实例的非静态方法和字段.但是,如果不知道要在哪个实例上运行,它就不能访问任何非静态的东西.
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!
}
}
此处,静态方法不知道应访问哪个 Test
实例.相反,如果它是一种非静态方法,则它将知道 x
引用了 this.x
(此处隐含了 this
),但是此
在静态上下文中不存在.
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.
但是,如果您提供对实例的访问权限,即使静态方法也可以访问 x
.
If, however, you provide access to an instance even a static method can access 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
}
}
这篇关于静态方法可以访问非静态实例变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!