Course contentsShow
← Java
Lesson 1723 of 2,87036. Lambda Expressions and Method ReferencesFree lesson

The 'this' Reference in Lambda Expressions

Understand that 'this' in a lambda refers to the enclosing instance, not the lambda itself, and its implications.

The 'this' Reference in Lambda Expressions

You'll learn how this behaves differently in lambdas compared to anonymous classes, and why it matters.

Understanding this in Lambdas

When you use this inside a lambda expression, it refers to the enclosing class instance—the object that contains the lambda—not the lambda itself. This is fundamentally different from anonymous inner classes, where this refers to the anonymous class instance.

Think of it this way: a lambda is like a lightweight function that "borrows" the context of its surrounding class. It doesn't create its own identity; it's more like a helper that lives within the outer object's world.

How This Works in Practice

public class MessagePrinter {
    private String prefix = "Message: ";
    
    public void printWithLambda() {
        Runnable lambda = () -> {
            // 'this' refers to the MessagePrinter instance
            System.out.println(this.prefix + "from lambda");
        };
        lambda.run();
    }
}

In the lambda above, this.prefix accesses the MessagePrinter instance's field directly. The lambda has no separate identity—it's part of the MessagePrinter object.

Why This Matters

This behavior is actually more intuitive and useful than anonymous classes. Since lambdas can capture instance variables and static fields (as you learned previously), having this refer to the enclosing instance maintains consistency. You can call instance methods, access fields, and interact with the outer object seamlessly:

Consumer<String> consumer = msg -> this.processMessage(msg);

Here, this.processMessage() clearly calls a method on the enclosing class instance.

Key Takeaway: In lambda expressions, this always refers to the enclosing class instance, never to the lambda itself, making lambdas feel like natural extensions of the containing object rather than separate entities.