ProLesson 4.10Intermediate3 min readUpdated 30 October 2026
Inner, static nested and anonymous classes
Classes inside classes. When to use a static nested class, an inner class, a local class or an anonymous class, and the memory trap to avoid.
Java lets you define a class inside another class. It keeps helper types close to where they're used and can hide them from the rest of the code. There are four kinds.
011. Static nested class
A static nested class is a normal class that happens to live inside another one. It doesn't need an object of the outer class. The classic use is the Builder pattern:
BuilderPattern.java
class Pizza {
private final String size;
private final boolean cheese;
private final boolean olives;
private Pizza(Builder b) {
size = b.size;
cheese = b.cheese;
olives = b.olives;
}
@Override
public String toString() {
return size + " pizza" + (cheese ? ", cheese" : "") + (olives ? ", olives" : "");
}
static class Builder { // static nested class
private String size = "medium";
private boolean cheese;
private boolean olives;
Builder size(String s) { size = s; return this; }
Builder cheese() { cheese = true; return this; }
Builder olives() { olives = true; return this; }
Pizza build() { return new Pizza(this); }
}
}
public class BuilderPattern {
public static void main(String[] args) {
Pizza p = new Pizza.Builder().size("large").cheese().olives().build();
System.out.println(p);
}
}large pizza, cheese, olives
Loading the rest of the lesson…