我正在尝试访问 Thread 匿名类中的实例变量。我在这里收到一个错误,说要使其静态。这里的要点是,如果我可以访问匿名类中的“this”关键字,并将其视为当前对象持有者,那么为什么它不能以非静态方式访问实例变量。
public class AnonymousThreadDemo {
int num;
public AnonymousThreadDemo(int num) {
this.num = num;
}
public static void main(String[] args) {
Thread thread = new Thread() {
@Override
public void run() {
System.out.println("Anonymous " + num); // Why cant we access num instance variable
System.out.println("Anonymous " + this); // This can be accessed in a nonstatic way
}
};
thread.start();
}
}
最佳答案
num
是一个非静态
字段,它属于一个特定的实例。您不能直接在 static main
中引用它,因为可以在不创建实例的情况下调用 static
方法。
this
实际上引用了thread
,它是一个局部变量,当你执行run
时,thread
必须已创建。
如果您尝试在 main
中引用 AnonymousThreadDemo.this
,您将得到相同的结果:
public static void main(String[] args) {
Thread thread = new Thread() {
@Override
public void run() {
System.out.println("Anonymous " + AnonymousThreadDemo.this); // compile error
}
};
thread.start();
}
<小时/>
这样就可以了,你可以在局部类中引用局部变量:
public static void main(String[] args) {
int num = 0;
Thread thread = new Thread() {
@Override
public void run() {
System.out.println("Anonymous " + num);
}
};
thread.start();
}
<小时/>
没关系,您可以在其方法中引用非静态局部类字段:
public static void main(String[] args) {
Thread thread = new Thread() {
int num = 0;
@Override
public void run() {
System.out.println("Anonymous " + num);
}
};
thread.start();
}
<小时/>
检查this了解更多。
关于java - 匿名线程类无法访问非静态实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50146785/