Sub topic 11
Scope and this: Lambdas vs Anonymous Classes
A lambda and an anonymous class can do the same job. Both can sort a list or run a task. They do not treat names the same way, though. This chapter shows how the word this and the names of your variables behave differently in each one.
You will learn:
- What scope means for a lambda.
- What
thisrefers to inside a lambda. - What
thisrefers to inside an anonymous class. - Why some variable names that work in an anonymous class fail in a lambda.
What Scope Means
Scope is the part of your code where a name can be used. A name can be a variable, a parameter, or a field. When you open a method body with {, you start a new scope. Variables you declare inside it exist only until the matching }.
A field is a variable that belongs to an object, declared inside the class but outside any method. The keyword this is a reference to the current object. You write this.name to mean "the name field of the object I am in right now."
Lambdas and anonymous classes differ in one key way:
- An anonymous class is a real class. It creates a new object and a new scope. Inside it,
thismeans that new object. - A lambda does not create a new object scope. It is lexically scoped. Lexically scoped means the lambda sees names exactly as the code around it sees them. Inside a lambda,
thismeans the same thing it means just outside the lambda.
Seeing the Difference in Code
The program below has a field called name in two places. One is in the ScopeDemo class. The other is in an anonymous class. Both the lambda and the anonymous class print this.name.
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();
}
}Save it as ScopeDemo.java, then compile and run it:
javac ScopeDemo.java
java ScopeDemoThe output is:
outer
innerHere is why:
- The lambda sits inside the
runmethod ofScopeDemo. In that method,thisis theScopeDemoobject, sothis.nameis"outer". - The anonymous class is a new object of its own. It declares its own
namefield. Inside itsrunmethod,thisis that anonymous object, sothis.nameis"inner".
Reaching the Outer Object from an Anonymous Class
What if code inside an anonymous class needs the outer object? Java has a special form for this: ClassName.this. This is called a qualified this. It means "the enclosing object of type ClassName."
A lambda never needs this form, because its plain this already points to the outer object.
The example below also overrides toString. The toString method decides how an object looks when you print it.
public class Greeter {
private String name = "Greeter";
@Override
public String toString() {
return "I am " + name;
}
void show() {
Runnable lambda = () -> System.out.println(this);
Runnable anon = new Runnable() {
@Override
public void run() {
System.out.println(this); // the anonymous object
System.out.println(Greeter.this); // the outer Greeter object
}
};
lambda.run();
anon.run();
}
public static void main(String[] args) {
new Greeter().show();
}
}The output looks like this:
I am Greeter
Greeter$1@1b6d3586
I am GreeterThe second line will show a different number on your machine. Greeter$1 is the name the compiler gives the first anonymous class inside Greeter. The anonymous class does not override toString, so Java prints its class name and a hash code. The lambda prints I am Greeter because its this is the Greeter object.
Lambdas Cannot Reuse Nearby Names
Because a lambda shares the scope around it, you cannot declare a variable or parameter inside a lambda with the same name as a local variable outside it. An anonymous class has its own scope, so it can reuse the name. Reusing a name in an inner scope is called shadowing. The inner name hides the outer one.
import java.util.function.Consumer;
public class ShadowDemo {
public static void main(String[] args) {
int x = 10;
// Each of these lines fails to compile if you uncomment it:
// Runnable bad1 = () -> { int x = 5; }; // error: x is already defined
// Consumer<Integer> bad2 = x -> System.out.println(x); // error: x is already defined
Runnable anon = new Runnable() {
@Override
public void run() {
int x = 5; // allowed: the anonymous class has its own scope
System.out.println(x);
}
};
anon.run(); // 5
Runnable lambda = () -> System.out.println(x);
lambda.run(); // 10
Consumer<Integer> ok = y -> System.out.println(x + y);
ok.accept(1); // 11
}
}The fix for the lambda is simple: pick a different name, like y.
Changing Fields from a Lambda
In the earlier chapter on capturing variables, you saw that a lambda can only read local variables that are effectively final. That rule does not apply to fields. A lambda captures this, not the field itself. The reference this never changes, so the lambda may update fields through it.
public class Counter {
private int count = 0;
void countThreeTimes() {
Runnable increment = () -> count++; // same as this.count++
increment.run();
increment.run();
increment.run();
System.out.println(count); // 3
}
public static void main(String[] args) {
new Counter().countThreeTimes();
}
}No this in a Static Method
A static method belongs to the class, not to any object. The main method is static. Inside a static method there is no current object, so this does not exist. A lambda written inside a static method also has no this. If you write this there, you get a compile error such as "non-static variable this cannot be referenced from a static context."
An anonymous class inside a static method still has its own this, because it creates its own object.
Side-by-Side Summary
| Question | Lambda | Anonymous class |
|---|---|---|
| Creates a new scope for names? | No, it shares the enclosing scope | Yes, it has its own scope |
| What does `this` mean? | The enclosing object | The anonymous object itself |
| How to reach the outer object? | Plain `this` | `OuterClass.this` |
| Can it reuse a nearby local variable name? | No, compile error | Yes, the inner name shadows the outer one |
| Can it declare its own fields? | No | Yes |
| `this` inside a static method? | Not available | Refers to the anonymous object |
Which One Should You Use?
Use a lambda for most short pieces of behavior. Its scope rules are simpler, since names mean the same thing inside and outside.
Use an anonymous class when you need something a lambda cannot do:
- The object needs its own fields to remember state.
- The code needs to refer to itself with
this. - The interface has more than one abstract method, so it is not a functional interface.
Exercises
Exercise
A class Box has a field String label = "box". Inside an instance method of Box, you write Runnable r = () -> System.out.println(this.label); and call r.run(). What is printed, and why?
Show answer
It prints "box". A lambda is lexically scoped, so this inside it refers to the enclosing Box object, and this.label is that object's field.
Exercise
Inside main you have String s = "hi";. Will Consumer<String> c = s -> System.out.println(s); compile? How do you fix it?
Show answer
No. A lambda shares the enclosing scope, so its parameter cannot reuse the name of the local variable s. Rename the parameter, for example Consumer<String> c = t -> System.out.println(t);.
Exercise
Inside an anonymous Runnable declared in an instance method of class Shop, how do you print the Shop object rather than the Runnable object?
Show answer
Use the qualified this: System.out.println(Shop.this);. A plain this would refer to the anonymous Runnable object.