Sub topic 9
Anonymous classes versus lambdas
This chapter assumes you know how anonymous classes are declared (covered in the previous chapter), what an interface with a single abstract method looks like, and how Comparator and Runnable work. Here you will compare the two ways to write a one-off implementation. You will see where they behave the same, where they differ, and when only an anonymous class will compile.
The same job, two syntaxes
Since Java 8, a lambda expression can replace many anonymous classes. Both examples below sort by length.
import java.util.Arrays;
import java.util.Comparator;
public class SortDemo {
public static void main(String[] args) {
String[] words = {"pear", "fig", "banana"};
Comparator<String> anonymous = new Comparator<String>() {
@Override
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
};
Comparator<String> lambda = (a, b) -> Integer.compare(a.length(), b.length());
Arrays.sort(words, anonymous);
System.out.println(Arrays.toString(words)); // [fig, pear, banana]
Arrays.sort(words, lambda);
System.out.println(Arrays.toString(words)); // [fig, pear, banana]
}
}The anonymous version spells out the class name, the method name, its modifiers, and its parameter types. The lambda supplies only the parameters and the body. The compiler recovers the rest from the target type, which is the type the expression is assigned to or passed as. Here the target type is Comparator<String>.
That is the first rule: a lambda needs a target type that is a functional interface. A functional interface has exactly one abstract method. Default methods, static methods, and methods inherited from Object such as equals do not count.
What only an anonymous class can do
An anonymous class is a real class with a body. A lambda is a compact way to supply one method. The gap between them shows up in four places.
| Capability | Anonymous class | Lambda |
|---|---|---|
| Implement an interface with several abstract methods | Yes | No |
| Extend a class, including an abstract class | Yes | No |
| Declare its own fields | Yes | No |
| Meaning of `this` | The anonymous object itself | The enclosing object |
| Declare a local variable with the same name as an enclosing local | Yes, in a new scope | No, compile error |
| Call a superclass constructor with arguments | Yes | Not applicable |
Extending a class and keeping state
public class AnonymousState {
static abstract class Task {
abstract void run();
}
public static void main(String[] args) {
Task t = new Task() {
private int calls;
@Override
void run() {
calls++;
System.out.println("calls = " + calls);
}
};
t.run(); // calls = 1
t.run(); // calls = 2
}
}Task is an abstract class, so a lambda cannot target it. Even with an interface, a lambda cannot declare a field like calls. You can emulate state in a lambda by capturing a mutable object, but the state then lives outside the lambda.
import java.util.concurrent.atomic.AtomicInteger;
public class CaptureDemo {
public static void main(String[] args) {
AtomicInteger calls = new AtomicInteger();
Runnable r = () -> System.out.println("calls = " + calls.incrementAndGet());
r.run(); // calls = 1
r.run(); // calls = 2
}
}The variable calls is effectively final, because it is never reassigned. The object it refers to is mutable. This works, but the state is visible to anything else holding the reference. In an anonymous class the field can be private.
Several abstract methods
public class ListenerDemo {
interface Listener {
void onStart();
void onStop();
}
public static void main(String[] args) {
Listener l = new Listener() {
@Override public void onStart() { System.out.println("start"); }
@Override public void onStop() { System.out.println("stop"); }
};
l.onStart();
l.onStop();
}
}Listener has two abstract methods, so no lambda can implement it. If you wrote Listener l = () -> {}; the compiler would report that Listener is not a functional interface.
The meaning of `this`
This is the difference that causes the most bugs when you convert code mechanically. Inside an anonymous class, this refers to the anonymous object. Inside a lambda body, this means the same thing it means just outside the lambda. A lambda does not introduce a new scope for this.
public class ThisDemo {
private final String name = "outer";
Runnable anonymous() {
return new Runnable() {
private final String name = "anon";
@Override
public void run() {
System.out.println(name); // anon
System.out.println(this.name); // anon
System.out.println(ThisDemo.this.name); // outer
}
};
}
Runnable lambda() {
return () -> System.out.println(this.name); // outer
}
public static void main(String[] args) {
new ThisDemo().anonymous().run();
new ThisDemo().lambda().run();
}
}In the anonymous class, you reach the enclosing object with ThisDemo.this, the same syntax used for inner classes. In the lambda, plain this already gives you that object. The reverse also holds. A lambda cannot refer to itself through this, so a lambda cannot call itself recursively the way an anonymous class can through this.
Scope and shadowing
An anonymous class body is a new scope for names. Its methods may declare locals and parameters that reuse the names of locals in the enclosing method. A lambda body shares the scope of the enclosing method, so redeclaring a name is an error.
public class ScopeDemo {
public static void main(String[] args) {
int limit = 10;
Runnable a = new Runnable() {
@Override
public void run() {
int limit = 5; // legal: shadows the enclosing local
System.out.println(limit); // 5
}
};
a.run();
// Runnable l = () -> { int limit = 5; };
// error: variable limit is already defined in method main(String[])
}
}Shadowing inside an anonymous class is legal but easy to misread. Many teams avoid it for that reason.
Capture rules are the same
Both forms capture local variables and parameters that are final or effectively final. A variable is effectively final if it is never assigned after initialization. Assigning to a captured variable, from inside or outside the body, is a compile error in both cases.
int total = 0;
Runnable r = () -> total++; // error: local variables referenced from a lambda
// expression must be final or effectively finalFields are different. Both forms can freely read and write fields of the enclosing object, because they reach the fields through a reference rather than copying a value.
How they compile
The two forms produce different artifacts, and this affects stack traces and memory.
- An anonymous class compiles to its own class file, named after the enclosing class with a number:
SortDemo$1.class,SortDemo$2.class, and so on, in source order. The class is loaded like any other class. - A lambda does not produce a class file for its body. The compiler turns the body into a private synthetic method in the enclosing class, with a name like
lambda$main$0. At run time, the first execution of the lambda expression goes through aninvokedynamiccall site, which asks the JVM to build an object implementing the functional interface.
Practical effects:
- A project with many anonymous classes has many small class files and loads many small classes. Lambdas avoid this.
- Stack traces show frames like
lambda$main$0and a generated class name for lambdas, while anonymous classes showSortDemo$1.compare. - A non-capturing lambda, one that uses no local variables or
this, can be reused by the JVM as a single instance. An anonymous class expression creates a new object each time it is evaluated.
Hidden outer references
An anonymous class created in an instance method always holds a reference to the enclosing object, even if its body never uses it. A lambda holds the enclosing this only if its body uses this, an instance field, or an instance method.
If you register a callback with a long-lived object, such as a static registry or a thread pool, the difference matters. The anonymous version keeps the whole enclosing object reachable. The lambda may not. In a static method, neither form has an enclosing instance.
public class Screen {
private final byte[] bigBuffer = new byte[10_000_000];
Runnable anonymousTask() {
return new Runnable() { // keeps Screen.this alive, and with it bigBuffer
@Override public void run() { System.out.println("tick"); }
};
}
Runnable lambdaTask() {
return () -> System.out.println("tick"); // captures nothing from Screen
}
}Do not rely on this as a guarantee of leak-free code. It describes how current compilers behave, and a lambda that touches any instance member captures this as well.
Choosing between them
A short guide:
- Use a lambda when the target is a functional interface and the body is short and stateless.
- Use an anonymous class when you must extend a class, implement several abstract methods, hold private state, or need
thisto mean the new object. - Use a named class or a method reference when the body is long or used in more than one place.
Common errors
- Writing
Listener l = () -> {...}for an interface with two abstract methods. Fix: use an anonymous class, or split the interface. - Redeclaring an enclosing local name inside a lambda. Fix: rename the variable.
- Using
thisin a lambda and expecting the lambda object. Fix: move to an anonymous class or a named class. - Mutating a captured local such as
count++. Fix: useAtomicInteger, a one-element array, or a field. - Passing a lambda where the parameter type is an abstract class. Fix: use an anonymous class.
Exercise
The following code compiles with an anonymous class and prints outer. A colleague converts it to a lambda and the output changes. Explain what changes and why.
public class Q {
private final String label = "outer";
Runnable make() {
return new Runnable() {
private final String label = "inner";
public void run() { System.out.println(label); }
};
}
}
Show answer
The original prints inner, not outer. The anonymous class declares its own field label, which shadows the outer field when label is written plainly. A lambda cannot declare fields, and this inside it is the enclosing Q. So the converted version prints outer. The converted version loses the field, and the output changes from inner to outer.
Exercise
Which of these targets can a lambda implement? (a) Runnable, (b) java.util.TimerTask (an abstract class), (c) an interface with two abstract methods and one default method, (d) Comparator<String>.
Show answer
Only (a) and (d). Runnable and Comparator are functional interfaces. Comparator also declares equals and has default and static methods, but these do not count as abstract methods. TimerTask is a class, and the interface in (c) has two abstract methods, so both need an anonymous class.
Exercise
A class registers new Runnable() { public void run() { System.out.println("tick"); } } with a static scheduler from an instance method. The body does not use the outer object. Why might the outer object still stay in memory, and how do you avoid it?
Show answer
An anonymous class created in an instance method holds a hidden reference to the enclosing instance whether or not its body uses it. The static scheduler keeps the Runnable alive, so the enclosing object stays reachable. Writing the task as a lambda that uses no instance members avoids the reference. A static nested class would also avoid it.