Sub topic 14
Choosing the right kind of nested class
This chapter assumes you know the four kinds of nested class (static nested, inner, local, anonymous), the Outer.this and outer.new Inner() syntax, effectively final capture, and how lambdas replace single-method anonymous classes. Here we turn that knowledge into a decision procedure.
Start from what the class needs
Pick the kind by asking what the class must reach and how widely it must be visible. Do not start from which syntax is shortest.
- Does the class need an enclosing instance (its fields or methods)?
- Does it need local variables or parameters from one method?
- Does it need a name, or is it used in exactly one place?
- Does it need its own state or multiple methods?
A class that needs no enclosing instance but uses one method's locals is a special case. A local class, anonymous class, or lambda is still the only way to capture those locals, so the diagram's first question applies to the instance, not to locals.
Default to static
Make a nested class static unless you can name the reason it needs an outer instance. A static nested class has no hidden reference to an outer object, so it is cheaper, can be created on its own, and cannot leak the outer object.
Typical uses are node types for data structures, builders, entries, and small value holders. Prefer private static when callers should never see the type.
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedStack<T> implements Iterable<T> {
private static class Node<T> {
final T value;
final Node<T> next;
Node(T value, Node<T> next) {
this.value = value;
this.next = next;
}
}
private Node<T> head;
public void push(T value) { head = new Node<>(value, head); }
public T pop() {
if (head == null) throw new NoSuchElementException();
T v = head.value;
head = head.next;
return v;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private Node<T> current = head;
@Override
public boolean hasNext() { return current != null; }
@Override
public T next() {
if (current == null) throw new NoSuchElementException();
T v = current.value;
current = current.next;
return v;
}
};
}
public static void main(String[] args) {
LinkedStack<String> s = new LinkedStack<>();
s.push("a");
s.push("b");
s.push("c");
for (String x : s) System.out.println(x); // c, b, a
}
}This example uses two kinds on purpose. Node is static because a node only needs its own value and link. If it were an inner class, every node would carry a pointer to the stack, which wastes memory for nothing. The iterator is anonymous because it needs the stack's head, it is used once, and callers need only the Iterator type.
Use an inner class when the object belongs to an owner
An inner class fits when each instance only makes sense relative to one outer object and keeps using its state. Iterators, views over a collection, and cursors are the standard cases. If the class is created in one place only and is short, an anonymous class is enough. If it is created from several methods, has a constructor with parameters, or is complex enough to deserve a name, use a named inner class.
Make inner classes private unless callers must create them. A public inner class forces callers to write outer.new Inner(), which is awkward. If you find yourself exposing that syntax, a static nested class that takes the outer object as a constructor argument is usually clearer, and it makes the dependency visible.
Use a local class for a named, method-scoped helper
A local class suits a helper that needs the method's variables and is used more than once in that method, or needs a constructor, several methods, or a name for readability. It is rare in practice. Often a private method or a private static nested class with explicit parameters is easier to read and test. Choose a local class only when capturing the method's variables saves real plumbing.
Anonymous class or lambda
Use a lambda when the target type is a functional interface (one abstract method) and the body needs no state of its own. Use an anonymous class when you need any of the following:
- a supertype that is an abstract class or a concrete class, not just an interface
- an interface with more than one abstract method
- fields that persist between calls
- a distinct
thisthat refers to the new object, not the enclosing one - extra helper methods or an initializer block
public class AnonymousChoice {
static abstract class Task {
abstract void run();
}
public static void main(String[] args) {
Runnable lambda = () -> System.out.println("lambda this is the enclosing scope");
Task counting = new Task() {
private int calls;
@Override
void run() {
calls++;
System.out.println("calls = " + calls);
}
};
lambda.run();
counting.run(); // calls = 1
counting.run(); // calls = 2
}
}Inside a lambda, this means the enclosing instance, and the lambda adds no new scope, so it cannot shadow a local variable. Inside an anonymous class, this is the anonymous object. If you port code between the two forms, check every this and every variable name that might now collide.
Compare the four kinds
| Kind | Holds outer instance | Can capture locals | Has a name | Typical use |
|---|---|---|---|---|
| Static nested | No | No | Yes | Nodes, builders, entries, helpers |
| Inner | Yes | No | Yes | Iterators and views tied to one owner |
| Local | Only in an instance method | Yes | Yes, in one method | Named helper using method variables |
| Anonymous | Only in an instance context | Yes | No | One-off implementation or subclass |
"Only in an instance context" matters. A local or anonymous class declared in a static method has no enclosing instance, so it cannot leak one. A local or anonymous class in an instance method does hold one, even if it never uses it.
Memory and lifetime as a deciding factor
An inner, local, or anonymous class created in an instance method stores a hidden reference to the outer object, usually in a synthetic field named this$0. As long as the nested object is reachable, so is the outer object, with everything it references. This matters when the nested object outlives the outer one, for example when it is stored in a static registry, handed to a thread pool, or registered as a long-lived listener.
import java.util.ArrayList;
import java.util.List;
public class Retention {
private static final List<Runnable> REGISTRY = new ArrayList<>();
private final byte[] big = new byte[1_000_000];
void registerRetaining() {
REGISTRY.add(new Runnable() {
@Override
public void run() { System.out.println("tick"); }
});
}
static Runnable detached() {
return new Runnable() {
@Override
public void run() { System.out.println("tick"); }
};
}
void registerDetached() {
REGISTRY.add(detached());
}
void registerLambda() {
REGISTRY.add(() -> System.out.println("tick"));
}
public static void main(String[] args) {
new Retention().registerDetached();
new Retention().registerLambda();
System.out.println(REGISTRY.size()); // 2
}
}The anonymous Runnable in registerRetaining never uses big, yet it holds the whole Retention object, and its megabyte array, as long as it sits in REGISTRY. Two fixes are shown: create it in a static method, or use a lambda that does not mention this or any instance member, because such a lambda captures nothing. Recent javac versions (JDK 18 and later) can also drop an unused outer reference from non-serializable inner classes, but do not depend on this. Write the code so the retention cannot happen.
Common mistakes
- Forgetting
static. A nested class that does not use the outer instance but is not static still carries the reference. Addstaticunless you need the outer object. - Inner classes in serialized types. Serializing an inner class instance also tries to serialize its outer object. Prefer static nested classes for anything serializable.
- Long-lived callbacks from instance methods. Anything stored in a static field, cache, or scheduler should not hold an outer instance unnecessarily.
- Replacing an anonymous class with a lambda blindly. The change alters
this, drops any state, and fails for abstract classes. - Deep nesting for organization only. If a nested class grows beyond a few dozen lines or is used by other classes, move it to its own file.
Exercise
A Cache class registers new Runnable() { public void run() { evictAll(); } } with a static ScheduledExecutorService from its constructor. Name the kind of class, say what problem it causes, and give one fix.
Show answer
It is an anonymous inner class created in an instance context, so it holds a hidden reference to the Cache that is alive as long as the scheduled task is. Because evictAll() is an instance method, the task legitimately needs the Cache. The cache therefore cannot be garbage collected until the task is cancelled. Fix it by keeping the ScheduledFuture and cancelling it in a close() method, or by holding the cache through a WeakReference inside a static nested task class that stops when the reference is cleared.
Exercise
Which kind of nested class would you choose for a Comparator used once, for the iterator of a custom collection that reads the collection's private array, and for a Builder of an immutable class? Give one reason for each.
Show answer
The Comparator is a lambda, because it is a functional interface used once and needs no state. The iterator is a private inner class (or an anonymous class if short), because it needs the collection's array and each iterator belongs to one collection. The Builder is a static nested class, because it is created before any instance of the built class exists, so there is no outer instance to attach to.