Reputation: 755
class MyClass1 {
int x = 10;
public static void main(String[] args) {
MyClass1 obj = new MyClass1();
obj.execute();
}
private void execute() {
Thread t = new Thread(new Runnable(){
@Override
public void run() {
System.out.println(this);
System.out.println(MyClass1.this.x);
}
});
t.start();
}
}
Here this refers to an object of anonymous inner class. That is why this.x does not work. But how can we use this to refer to MyClass1 object? Please explain. When we do Sysout(this), it prints out com.java.MyClass1$1@3cd7c2ce where $ specify inner class object. I am not clear on this.
Upvotes: 1
Views: 328
Reputation: 690
The method in which you are creating the anonymous inner class is not an instance method but a static method.
Also, the syntax is MyClass1.this.x
, not this.x
.
To make it work, rewrite it like this:
class MyClass1 {
int x= 10;
public static void main(String[] args) {
new MyClass1().main();
}
private void main() {
Thread t= new Thread(new Runnable(){
@Override
public void run() {
System.out.println(this);
System.out.println(MyClass1.this.x);
}
});
t.start();
}
}
Upvotes: 3
Reputation: 754
You can't use this
keyword in a static method because this
points to an instance of the class and in the static method, you don't have an instance.
Upvotes: 5