Sub topic 11
Scope and this: Lambdas vs Anonymous Classes
Lambdas and anonymous classes can do the same job. They still differ in one way that can surprise you: what names mean inside them. This chapter covers what this refers to in each, and which variable names you are allowed to reuse.
What Is Scope?
Scope is the part of your code where a name, such as a variable, can be used. A block of code in curly braces { } usually has its own scope.
An anonymous class creates a new scope. It is a real class with its own fields and methods.
A lambda does not create a new scope. Its body shares the scope of the code around it. That surrounding code is called the enclosing scope.
What Does this Mean?
The keyword this means "the current object." The current object depends on where you write this.
- Inside a lambda,
thisis the object of the enclosing class. The lambda is not an object you can talk to throughthis. - Inside an anonymous class,
thisis the anonymous object itself.
Here is an example with both:
public class ScopeDemo {
private String name = "outer";
void run() {
Runnable lambda = () -> System.out.println(this.name); // this = ScopeDemo instance
Runnable anon = new Runnable() {
private String name = "inner";
@Override
public void run() {
System.out.println(this.name); // this = the anonymous Runnable
}
};
lambda.run(); // outer
anon.run(); // inner
}
public static void main(String[] args) {
new ScopeDemo().run();
}
}The lambda prints outer because this is the ScopeDemo object. The anonymous class prints inner because this is the anonymous Runnable, which has its own name field.
Reusing Variable Names
Shadowing means declaring a new variable with the same name as one in an outer scope. The new one hides the old one.
An anonymous class has its own scope, so it can shadow a local variable. A lambda shares the enclosing scope, so it cannot. If you try, the compiler reports an error.
public class ShadowDemo {
public static void main(String[] args) {
int x = 10;
// Not allowed: x is already defined in this scope.
// Runnable bad = () -> { int x = 5; };
// Runnable bad2 = x -> {}; // parameter name clashes too
Runnable anon = new Runnable() {
@Override
public void run() {
int x = 5; // allowed: new scope hides the outer x
System.out.println(x);
}
};
anon.run(); // 5
Runnable lambda = () -> System.out.println(x);
lambda.run(); // 10
}
}The same rule covers lambda parameters. A lambda parameter cannot have the same name as a local variable in the enclosing method.
Side-by-Side Summary
| Question | Lambda | Anonymous class |
|---|---|---|
| Creates a new scope? | No | Yes |
| `this` refers to | Enclosing object | The anonymous object |
| Can redeclare an outer local name? | No, compile error | Yes, it shadows |
| Can have its own fields? | No | Yes |
Exercise
A class has a field String label = "A". Inside one of its methods, you write Runnable r = () -> System.out.println(this.label); and call r.run(). What is printed, and why?
Show answer
It prints "A". Inside a lambda, this refers to the enclosing object, so this.label reads the field of the class that contains the method.
Exercise
Why does int count = 0; Runnable r = () -> { int count = 1; }; fail to compile, while the same inner declaration works inside an anonymous class's run method?
Show answer
A lambda body shares the enclosing scope, so declaring count again is a duplicate variable. An anonymous class creates a new scope, so its count shadows the outer one.