1
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.

Oneiros
  • 4,328
  • 6
  • 40
  • 69
Payal Bansal
  • 725
  • 5
  • 17

2 Answers2

5

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.

Itzik Shachar
  • 744
  • 5
  • 16
3

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();
    }
}
dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
Rolf Schäuble
  • 690
  • 4
  • 15
  • I understood that here this refers to object of anonymous inner class. So if it is an instance method, still this refers to anonymous inner class , then how can you refer it as MyClass1.this.x? I mean how can we use this to refer to MyClass1 obj? I am still not clear on this. – Payal Bansal May 24 '17 at 14:40
  • In this example, an instance method of MyClass1 creates an inner class. The inner class gets a 'hidden' field of type `MyClass1`, to which you can refer in the code by `MyClass1.this`. – Rolf Schäuble May 24 '17 at 14:46