a shot of dev knowledge

Related tags

What is Class.this in Java?

SomeClass.this is used inside anonymous classes to refer to the enclosing class.

Here’s an example:

class Enclosing {
    void method(Enclosing other) {
        // ...
    }

    void otherMethod() {
        new Runnable() {
            public void run() {
                method(this); // Does not compile. 'this' is a Runnable!

                method(Enclosing.this); // Compiles fine.
            }
        }.run();
    }
}

In the code above, this refers to an object of the class where it is used (i.e., Runnable). To refer to the outer Enclosing class object, Enclosing.this can be used.

svg viewer

Code

Let’s take a look at a working example of how Enclosing.this can be used:

class Enclosing {
    void method(Enclosing other) {
        System.out.println("Accessing method");
    }

    void otherMethod() {
        new Runnable() {
            public void run() {
                // method(this); // Does not compile. 'this' is a Runnable!

                method(Enclosing.this); // Compiles fine.
            }
        }.run();
    }

    public static void main( String args[] ) {
        Enclosing e = new Enclosing();
        e.otherMethod();
    }  
}

Related tags

RELATED COURSES
View all Courses
Related Courses
Related Courses
View all Courses

Keep Exploring