Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

class
method
this

What is Class.this in Java?

Educative Answers Team

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

class
method
this
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring