this and super Semantics: Key Differences
What you'll learn: How this and super behave differently inside lambdas versus anonymous classes—a subtle but important distinction when converting code.
The Core Difference
When you use this inside an anonymous class, it refers to the anonymous class instance itself. But when you use this inside a lambda expression, it refers to the enclosing class instance—the class that contains the lambda.
This difference matters because lambdas don't create a new object with their own identity; they're more like code blocks that "borrow" the surrounding context. Anonymous classes, however, are full objects with their own this reference.
Understanding Through Context
Imagine you're in a meeting (the enclosing class). If you create an anonymous class, it's like inviting a guest speaker who says "I" to mean themselves. If you write a lambda, it's like taking notes in your own voice—"I" still means you, not the notes.
Anonymous class:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(this.getClass()); // Prints the anonymous ActionListener class
}
});
Lambda:
button.addActionListener(e -> {
System.out.println(this.getClass()); // Prints the ENCLOSING class, not ActionListener
});
The same distinction applies to super—in an anonymous class, super refers to its direct parent class. Lambdas don't have their own superclass, so super refers to the enclosing class's parent.
Why This Matters
When converting anonymous classes to lambdas, if your code uses this or super, the behavior will change. Only convert when this refers to the enclosing instance anyway, or when this isn't used at all.
Key Takeaway: this in a lambda refers to the enclosing class instance; this in an anonymous class refers to the anonymous class itself—understand this before converting between them.