Sub topic 9
Anonymous Classes Versus Lambdas
Prerequisites: you should know interfaces, abstract classes, method overriding, instance and static members, and basic Java generics. You should also understand that a functional interface has exactly one abstract method.
An anonymous class is a class expression without a declared class name. It creates one object and provides an implementation at the same time. A lambda expression is a shorter implementation of one abstract method in a functional interface.
The basic replacement
This anonymous class sorts strings by their 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));
Arrays.sort(words, lambda);
System.out.println(Arrays.toString(words));
}
}Both variables contain a Comparator<String>. The lambda is valid because Comparator has one abstract method: compare.
A lambda can use several equivalent forms:
Comparator<String> a = (x, y) -> Integer.compare(x.length(), y.length());
Comparator<String> b = (x, y) -> {
int result = Integer.compare(x.length(), y.length());
return result;
};Use the expression form for one short operation. Use the block form when the implementation needs several statements.
Important differences
A lambda does not create a new class scope in the same way as an anonymous class. In particular, this has different meanings.
- Inside an anonymous class,
thisrefers to the anonymous object. - Inside a lambda,
thisrefers to the enclosing object. - An anonymous class can declare its own instance fields.
- A lambda cannot declare fields or extend an abstract class.
- A lambda can target only a functional interface.
- An anonymous class can implement an interface with several abstract methods, or extend an abstract class.
For example, this anonymous class keeps state between calls:
public class AnonymousState {
static abstract class Task {
abstract void run();
}
public static void main(String[] args) {
Task task = new Task() {
private int calls;
@Override
void run() {
calls++;
System.out.println("calls = " + calls);
}
};
task.run();
task.run();
}
}The output is:
calls = 1
calls = 2A lambda cannot replace this code directly because Task is an abstract class, not a functional interface. Even if Task were replaced with a functional interface, the lambda could not declare the calls field itself. State would need to live in an enclosing object or a mutable holder.
Captured variables
Both forms can read local variables and parameters when those variables are effectively final. A variable is effectively final when it is assigned once and never changed afterward.
import java.util.function.IntUnaryOperator;
public class CaptureDemo {
static IntUnaryOperator add(int amount) {
return value -> value + amount;
}
public static void main(String[] args) {
IntUnaryOperator addFive = add(5);
System.out.println(addFive.applyAsInt(7)); // 12
}
}The returned lambda keeps a copy of amount. This is why changing amount after capturing it is not allowed.
Choosing between them
| Requirement | Lambda | Anonymous class |
|---|---|---|
| Implement one abstract interface method | Yes | Yes |
| Extend an abstract class | No | Yes |
| Declare instance fields | No | Yes |
| Use the enclosing object's `this` | Yes | No |
| Provide several method implementations | No | Yes |
Anonymous classes remain useful when their extra structure communicates a real design need. Otherwise, a lambda usually makes short callback and strategy code easier to read.
Exercise
Why can a lambda replace the Comparator anonymous class but not the Task anonymous class in this chapter?
Show answer
Comparator is a functional interface with one abstract method. Task is an abstract class, and lambdas can target functional interfaces only.