Sub topic 3
Anonymous Classes Versus Lambdas
Assume you know Java classes, interfaces, inheritance, and static members. This chapter focuses on how nested declarations affect behavior, access, and memory.
Anonymous Classes Versus Lambdas
An anonymous class creates one unnamed class and one object. It can implement an interface or extend a class. A lambda creates a function-like value for a functional interface, which has exactly one abstract method.
import java.util.Comparator;
public class CompareDemo {
public static void main(String[] args) {
Comparator<String> anonymous = new Comparator<>() {
@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());
}
}Use a lambda for short behavior with no class inheritance or independent fields. Use an anonymous class when you need to extend an abstract class, declare fields, override several methods, or use a distinct this.
Private Access Between Nested Classes
A nested class and its enclosing class may access each other’s private members. This supports tightly coupled implementation details without making those details public.
What Nested Classes May Declare
Nested classes may contain fields, methods, constructors, nested types, and access modifiers. A static nested class cannot directly use an outer object’s instance fields. A non-static inner class can, because every instance has an enclosing object.
Hidden Outer References and Memory Retention
A non-static inner object normally stores a hidden reference to its enclosing object. Therefore, keeping the inner object alive also keeps the outer object alive. This can retain large object graphs longer than intended, especially when an inner object is placed in a long-lived listener or executor.
Use a static nested class when the nested object does not need the outer instance. Make captured references explicit when lifetime matters.
How Nested Classes Compile
The compiler usually writes nested classes as separate class files. For example, Outer.Inner commonly becomes Outer$Inner.class. An anonymous class often receives a numbered name such as Outer$1.class. These names are implementation details, not source-level type names.
Choosing the Right Kind
| Need | Suitable choice |
|---|---|
| Helper type without an outer object | Static nested class |
| Type coupled to one outer instance | Inner class |
| One short, local implementation | Anonymous class |
| One-method behavior | Lambda |
Exercise
When should an anonymous class be preferred over a lambda?
Show answer
Prefer it when the object must extend a class, store its own fields, override multiple methods, or have its own this.