Unlike a lambda, an anonymous class creates its own object, so this inside its methods refers to that anonymous instance, letting it shadow a field of the same name from the enclosing class.
class Reporter {
String name = "outer-reporter";
Runnable asAnonymous() {
return new Runnable() {
String name = "anon-reporter";
@Override
public void run() {
System.out.println("Anonymous this.name: " + this.name);
}
};
}
}
new Reporter().asAnonymous().run();
Anonymous this.name: anon-reporter
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27