Java: Class.this

Johnny Jazz picture Johnny Jazz · Apr 3, 2011 · Viewed 35.3k times · Source

I have a Java program that looks like this.

public class LocalScreen {

   public void onMake() {
       aFuncCall(LocalScreen.this, oneString, twoString);
   }
}

What does LocalScreen.this means in aFuncCall?

Answer

aioobe picture aioobe · Apr 3, 2011

LocalScreen.this refers to this of the enclosing class.

This example should explain it:

public class LocalScreen {
    
    public void method() {
        
        new Runnable() {
            public void run() {
                // Prints "An anonymous Runnable"
                System.out.println(this.toString());
                
                // Prints "A LocalScreen object"
                System.out.println(LocalScreen.this.toString());
                
                // Won't compile! 'this' is a Runnable!
                onMake(this);
                
                // Compiles! Refers to enclosing object
                onMake(LocalScreen.this);
            }
            
            public String toString() {
                return "An anonymous Runnable!";
            }
        }.run();
    }
    
    public String toString() { return "A LocalScreen object";  }
    
    public void onMake(LocalScreen ls) { /* ... */ }
    
    public static void main(String[] args) {
        new LocalScreen().method();
    }
}

Output:

An anonymous Runnable!
A LocalScreen object

This post has been rewritten as an article here.