Sub topic 14
Choosing the Right Kind of Nested Class
Assume you can write and compile Java classes, use access modifiers, distinguish instance from static members, and work with interfaces, abstract classes, and basic generics. This chapter focuses on design choices rather than syntax alone.
A nested class is declared inside another class. Java has four useful forms:
- A static nested class belongs to the enclosing type, not to one enclosing object.
- An inner class is a non-static member class tied to an enclosing object.
- A local class is declared inside a method or block.
- An anonymous class creates one unnamed implementation or subclass at an expression.
Compare the choices
| Kind | Needs an outer object? | Best use | Main cost |
|---|---|---|---|
| Static nested | No | Helper type or builder grouped with its owner | Cannot directly use outer instance fields |
| Inner member | Yes | Object that needs the outer object's state | Retains an outer reference |
| Local | Usually yes, if non-static | Small implementation used in one method | Limited visibility and reuse |
| Anonymous | Depends on its target | One short custom implementation | Can become hard to read |
| Lambda | No separate class declaration | One behavior for a functional interface | Cannot extend a class or hold independent fields |
Use a static nested class for type-level helpers
Choose a static nested class when the type is conceptually part of its enclosing class but does not need a particular enclosing instance. Builders are a common example:
public final class Report {
private final String title;
private Report(Builder builder) {
this.title = builder.title;
}
public static final class Builder {
private String title = "Untitled";
public Builder title(String title) {
this.title = title;
return this;
}
public Report build() {
return new Report(this);
}
}
@Override
public String toString() {
return title;
}
public static void main(String[] args) {
Report report = new Report.Builder()
.title("Monthly results")
.build();
System.out.println(report);
}
}A static nested class can access private members of its enclosing class. It cannot use Report.this, because no Report object is attached to it.
Use an inner class when identity matters
An inner class is appropriate when each nested object belongs to one outer object and must work with that object's state. Create it with outer.new Inner():
public class Account {
private int balance;
public class Deposit {
public void add(int amount) {
balance += amount;
}
public Account owner() {
return Account.this;
}
}
public int balance() {
return balance;
}
public static void main(String[] args) {
Account account = new Account();
Account.Deposit deposit = account.new Deposit();
deposit.add(50);
System.out.println(account.balance()); // 50
System.out.println(deposit.owner() == account); // true
}
}The expression Account.this names the particular enclosing object. Prefer an inner class only when this relationship is meaningful. Otherwise, a static nested class avoids hidden state and outer-object retention.
Choose local, anonymous, or lambda by scope
Use a local class when a method needs a small named type with more than one method or with its own fields. Use an anonymous class for one immediate implementation, especially when extending an abstract class. Use a lambda when the target is a functional interface, such as Runnable or Comparator<T>, and the behavior is short.
import java.util.Comparator;
public class ChoiceDemo {
public static void main(String[] args) {
Comparator<String> byLength =
(first, second) -> Integer.compare(first.length(), second.length());
System.out.println(byLength.compare("cat", "elephant"));
}
}A lambda cannot extend an abstract class, declare independent instance fields, or provide multiple unrelated methods. An anonymous class can do all three within its declared type.
Check lifetime and compiled form
An inner object normally stores a hidden reference to its outer object. A long-lived inner object, such as a task kept by a scheduler, can therefore keep the outer object alive. Use a static nested class when that retention is unnecessary.
The compiler represents nested declarations in separate class files, commonly named Outer$Inner.class. This name is an implementation detail, not a reason to access those files directly.
Exercise
You need a reusable Builder that does not read fields from any particular product instance. Which nested kind should you choose, and why?
Show answer
Choose a static nested class. It groups the builder with the product without storing a hidden reference to a product object.