Lambda: this inside an anonymous class refers to the anonymous instance itself

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.

Code
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();
Output
Anonymous this.name: anon-reporter
Advertisement
More in JAVA

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

© Java Coding Hub · About · Contact · Privacy · Terms