Stage 2: Object-oriented programming, lesson 6 of 10

Nested, inner and anonymous classes

Intermediate3 min read@since 9Code runs on your Java 25
Explain it forThe essentials plus production detail and pitfalls.

Java lets you declare classes inside other classes:

  • Static nested class: static class Builder inside Pizza. It doesn't need an outer object and is the most common kind (builders, private helpers).
  • Inner class (non-static): each instance is tied to an outer instance and can read its fields.
  • Local class: declared inside a method; rarely used.
  • Anonymous class: declared and created in one expression, new Comparator<>() { … }. Since Java 8 a lambda usually replaces it when the interface has one method.

Rule of thumb: make nested classes static unless they genuinely need the outer object.

Example

Java
public class Pizza {
    private final String size;
    private final List<String> toppings;

    private Pizza(Builder b) {
        this.size = b.size;
        this.toppings = List.copyOf(b.toppings);
    }

    public static class Builder {                   // static nested class
        private String size = "Medium";
        private final List<String> toppings = new ArrayList<>();
        public Builder size(String s) { this.size = s; return this; }
        public Builder topping(String t) { toppings.add(t); return this; }
        public Pizza build() { return new Pizza(this); }
    }
}

Pizza p = new Pizza.Builder().size("Large").topping("Paneer").build();

Old way vs new way

Anonymous class
Runnable task = new Runnable() {
    @Override
    public void run() {
        System.out.println("Hi");
    }
};
Lambda (Java 8+)
Runnable task = () -> System.out.println("Hi");

Common mistake

Leaving a nested class non-static by default. It silently captures the outer instance, costs memory and can leak it.

Under the hood

An inner (non-static) class keeps a hidden reference to its outer object. If the inner instance outlives the outer one (a listener, a callback, a cached task), the outer object can't be garbage collected, a classic memory leak. Anonymous classes compile to separate class files (Outer$1.class); lambdas don't.

Check yourself

How do you create an instance of a static nested class?

How this connects

Where this leads

You've reached the end of this thread. Try a learning path for what's next.

Was this lesson helpful?

Finished reading? Mark it complete to track your progress.