Search code examples
javaandroidanonymous-class

who is 'this' inside an anonymous class implementation?


I can't figure out what is the object that this is reference to inside an anonymous class method. Two examples:

  1. If i implement an anonymous implementation for onClick, e.g:
View.setOnClickListener(new View.onClick() {
    public void onClick(View v) {
        ...
        this.   //to which object this refers?
   }
}

2.If let's say i have the following interface:

interface  WebResponseHandler {
    public void onWebResponseFinished(String jsonString)
}

and inside some class I'm defining a variable that implements the above interface:

private onInitWebResponseHandler = new VolleyHandler.WebResponseHandler() {
    public void onWebResponseFinished(String jsonString) {
            .....
            this    // to which object this refers to?
    }
}

I was surprised that in the second example the this refers to the class that private onInitWebResponseHandler is part from and not refers to onInitWebResponseHandler directly


Solution

  • Let's test it:

    public class Test {
    
        private String s = "Test Class";
    
        public void myMethod() {
    
            System.out.println("this.s: " + this.s);
    
            new Callable<String>() {
                private String s = "Callable Class";
    
                @Override
                public String call() {
                    System.out.println("this.s: " + this.s);
                    System.out.println("Test.this.s: " + Test.this.s);
                    return null;
                }
            }.call();
        }
    
    
        public static void main(String[] args) {
            new Test().myMethod();
        }
    }
    

    It prints

    this.s: Test Class
    this.s: Callable Class
    Test.this.s: Test Class
    

    So the this in the anonymous class is the anonymous class

    EDIT: Added Test.this.s as pointed out by Angel Koh