Video in progress
Does `this` inside an anonymous class mean the same thing as `this` inside a lambda?
No. In an anonymous class, this is the new object of that anonymous class. A lambda doesn't create a new scope: its this means the enclosing class's object.
📖 Answer
public class Greeter {
private final String name = "Greeter";
void run() {
Runnable anon = new Runnable() {
@Override public void run() {
System.out.println(this.getClass().getSimpleName()); // "": an anonymous class
}
@Override public String toString() { return "anon"; }
};
Runnable lambda = () -> System.out.println(this.name); // "Greeter"
anon.run();
lambda.run();
}
}
An anonymous class is a real inner class: it can have its own fields and toString(), and it keeps a hidden reference to the outer object (if it was created in an instance method of the outer class). To reach the outer object you have to write Greeter.this.name.
A lambda works like a function: this and super are those of the enclosing class, and inside a lambda you can't declare a local variable with the same name as an outer one.
This is where people often slip when working with this in a listener or callback. One more point: if a lambda doesn't use this, it doesn't hold on to the outer object, so there is less risk of a memory leak.
Sign up to mark studied questions and save your progress.