Trusted answers to developer questions

What is Class.this in Java?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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
Attributions:
  1. undefined by undefined
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?