This In Lambdas Versus Anonymous Classes

Compare this inside an anonymous class with this inside a lambda: the anonymous instance names its own class, the lambda names the enclosing one.

JavaData Integrity

Code

snippet
import java.util.function.Supplier;

public class ThisScopeDemo {

    private final String owner = "enclosing instance";

    // 匿名类 (anonymous class):内部的 this 指向匿名实例自己
    Supplier<String> viaAnonymous() {
        return new Supplier<String>() {
            @Override
            public String get() {
                return "this = " + this.getClass().getName();
            }
        };
    }

    // lambda 没有 this:这里的 this 沿用外层 ThisScopeDemo 实例
    Supplier<String> viaLambda() {
        return () -> "this = " + this.getClass().getName();
    }

    public static void main(String[] args) {
        ThisScopeDemo demo = new ThisScopeDemo();
        System.out.println("anonymous -> " + demo.viaAnonymous().get());
        System.out.println("lambda    -> " + demo.viaLambda().get());
    }
}

This In Lambdas Versus Anonymous Classes: reading the source

This In Lambdas Versus Anonymous Classes is built around the class ThisScopeDemo and the functions get and main.

Watch out for

  • The project needs no additions before this runs.

Using it

Signature: public String get()

The run emits 2 labeled sections — anonymous ->, lambda -> — one per step.

Treat main as the orchestrator calling get in a fixed order.

Key statements

return () -> "this = " + this.getClass().getName();
return "this = " + this.getClass().getName();

Interactive Tools for This Topic

FAQ

What does This In Lambdas Versus Anonymous Classes print when run?
Execute the whole file; each printed line is prefixed with a label like `anonymous ->`, `lambda ->`.