[英]Anonymous thread class not able to access non static instance variables
I am trying to access instance variable inside a Thread anonymous class . 我正在尝试访问Thread匿名类内的实例变量。 I am getting an error here saying to make it static .
我在这里说要使其静态化时出现错误。 The point here is if i can access "this" keyword inside the anonymous class which treats it as its current object holder, then why is it not able to access the instance variables in a non static way .
这里的重点是,如果我可以访问将其视为当前对象持有者的匿名类中的“ 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
is a non static
field, it belongs to a specific instance. num
是一个non static
字段,它属于特定实例。 You can not reference it in static main
directly, because a static
method can be called without creating an instance. 您不能直接在
static main
引用它,因为可以在不创建实例的情况下调用static
方法。
this
is actually referencing thread
, it is a local variable, when you execute run
, the thread
must have been created. this
实际上是在引用thread
,它是一个局部变量,当您执行run
,必须已创建thread
。
If you try reference AnonymousThreadDemo.this
in main
, you will get same result: 如果尝试在
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();
}
This is ok, you can reference a local variable in local class: 可以,您可以在本地类中引用本地变量:
public static void main(String[] args) {
int num = 0;
Thread thread = new Thread() {
@Override
public void run() {
System.out.println("Anonymous " + num);
}
};
thread.start();
}
This is ok, you can reference a non static local class field in its method: 可以,您可以在其方法中引用一个非静态的本地类字段:
public static void main(String[] args) {
Thread thread = new Thread() {
int num = 0;
@Override
public void run() {
System.out.println("Anonymous " + num);
}
};
thread.start();
}
num
is non static that means it will come after static main in the memory. num
是非静态的,这意味着它将在内存中的静态main之后。 Hence when main will try to point num
it won't be available in the memory ie. 因此,当main将尝试指向
num
,它将在内存中不可用,即。 It still won't be declared yet. 它仍然不会被宣布。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.