Skip to content
notes.vinhnq.com

Search

OOP & DesignMid21 min read

Nested classes in Java: static nested, inner, local and anonymous classes, and lambdas

Review 11 cards
On this page

Enums and nested classes series: 1. Enums are classes · 2. Enums in production · 3. Nested classes and lambdas

Picking the wrong kind of nested class has real consequences: an inner class registered as a listener can pin a 50 MB object in memory forever. After this post you’ll choose correctly between static nested, inner, local and anonymous classes, lambdas and records, and be able to explain effectively final. The exercises include Lab 07 from the Hỏi Dân IT material with a complete solution; you don’t need part 1 first, since the OrderStatus enum is written out in full here. All code targets Java 21.

1. Nested classes: the four kinds

Key idea: the four kinds differ in two ways: whether they’re tied to an instance of the outer class, and where they can be used. Default to static nested.

Kind Declared where Tied to an outer instance Can access Typical use
Static nested class In the class body, with static No Outer’s static members (including private) Builders, data-structure nodes, helper DTOs
Inner class In the class body, without static Yes (Outer.this) All members of the outer instance Collection iterators, views over outer data
Local class In a method/block, named Yes, in a non-static context Outer plus effectively final locals A helper used several times in one method
Anonymous class Inline in a new expression, unnamed Yes, in a non-static context Same as local classes Implementing an interface/class once

Nested records, enums and interfaces (including ones declared inside methods, since Java 16) are implicitly static.

flowchart TD
  A["I need a helper type for this class"] --> B{"Just a function of a single-method interface?"}
  B -->|Yes| L["Lambda or method reference"]
  B -->|No| C{"Needs state of a specific outer instance?"}
  C -->|No| D{"Immutable data?"}
  D -->|Yes| R["Nested record (implicitly static)"]
  D -->|No| S["Static nested class"]
  C -->|Yes| E{"Used only inside one method?"}
  E -->|No| I["Inner class"]
  E -->|"Yes, once"| AN["Anonymous class"]
  E -->|"Yes, several times"| LC["Local class"]

1.1. Static nested classes

Key idea: a static nested class is a top-level class living in another class’s namespace. It holds no reference to an outer instance, yet it can access the outer’s private members (and vice versa).

The classic example is a Builder:

public final class HttpCall {
    private final String url;
    private final String method;
    private final Map<String, String> headers;
    private final Duration timeout;

    private HttpCall(Builder b) {
        this.url = b.url;
        this.method = b.method;
        this.headers = Map.copyOf(b.headers);
        this.timeout = b.timeout;
    }

    public static Builder to(String url) { return new Builder(url); }

    public static final class Builder {
        private final String url;
        private String method = "GET";
        private final Map<String, String> headers = new LinkedHashMap<>();
        private Duration timeout = Duration.ofSeconds(5);

        private Builder(String url) { this.url = Objects.requireNonNull(url, "url"); }

        public Builder method(String method) { this.method = method; return this; }
        public Builder header(String name, String value) { headers.put(name, value); return this; }
        public Builder timeout(Duration timeout) { this.timeout = timeout; return this; }
        public HttpCall build() { return new HttpCall(this); }
    }
}

HttpCall call = HttpCall.to("https://api.example.com/orders")
        .method("POST")
        .header("Content-Type", "application/json")
        .build();

The builder must be static: while you’re using it, no HttpCall exists yet to act as the outer instance. Other JDK examples: HashMap.Node, Map.Entry, AbstractMap.SimpleEntry.

1.2. Inner classes and the hidden outer reference

Key idea: an inner (non-static) class is tied to an outer instance: you need an outer object to create it, and it uses the outer’s fields as its own. The price is that every inner object holds a strong reference to the outer.

public class Playlist {
    private final List<String> songs = new ArrayList<>();
    private int version;

    public class Cursor {
        private int index;
        private final int expectedVersion = version;   // reads the outer's field

        public String next() {
            if (version != expectedVersion) throw new ConcurrentModificationException();
            return songs.get(index++);                 // same as Playlist.this.songs
        }
    }
}

Playlist playlist = new Playlist();
Playlist.Cursor cursor = playlist.new Cursor();        // outer.new Inner() syntax
  • The compiler adds a hidden field final Playlist this$0 to the inner class, plus a hidden constructor parameter.
  • That’s how ArrayList.iterator() works (ArrayList.Itr is an inner class). The right use of an inner class: a helper object that only makes sense attached to its main object.
  • Since Java 16, inner classes may declare static members (previously a compile error).
JDK 18 drops this$0 when the outer is unused, and the Serializable exception

1.3. Local classes

Key idea: a local class is declared inside a method or block, has a name, and is only usable in that scope. It can read the outer’s fields and effectively final locals (assigned exactly once).

void exportReport(List<Order> orders, String tenant) {
    class Row {
        final String id;
        final String amount;
        Row(Order o) {
            this.id = tenant + "-" + o.id();            // uses a local variable of the method
            this.amount = o.total().toPlainString();
        }
        String toCsv() { return id + "," + amount; }
    }
    orders.stream().map(Row::new).map(Row::toCsv).forEach(System.out::println);
}

Local classes are rare in modern code because lambdas or local records cover most cases. Note: local records, local enums and local interfaces (Java 16+) are implicitly static, so they cannot read local variables or this of the enclosing method.

For example, record R(int v) { String show() { return prefix + v; } } with prefix being a local variable is a compile error. Pass the value in as a record component instead.

1.4. Anonymous classes

Key idea: an anonymous class is declared and instantiated in one expression, with no name. It can implement an interface or extend a class (including an abstract one), and can have fields and several methods.

Comparator<Order> byTotalDesc = new Comparator<>() {
    @Override
    public int compare(Order a, Order b) {
        return b.total().compareTo(a.total());
    }
};

Before Java 8, this was the only way to pass “a function” around. Today, for single-abstract-method interfaces, lambdas replace them almost entirely. Anonymous classes still earn their place when you need to extend an abstract class, implement a multi-method interface, or keep state.

2. Effectively final: why lambdas and anonymous classes only see “assigned once” locals

Key idea: a lambda may run after the method has returned, even on another thread, so the compiler copies the local variable’s value into it. Allow reassignment and the copy and the original would diverge, so Java forbids it outright.

Local variables live on the method’s stack; the copy lives in the lambda object (as a field or hidden parameter). The rule covers lambdas, anonymous classes and local classes.

int count = 0;
Runnable r = () -> count++;   // error: local variables referenced from a lambda expression
                              //        must be final or effectively final

The rule only applies to local variables. Object fields can be read and written freely, because the lambda captures this, not a copy of the field. For basic examples, see Java basics part 2.

3. How anonymous classes and lambdas really differ

Key idea: a lambda isn’t “short syntax for an anonymous class”. They differ in this, in target type, in state, and in how the JVM runs them.

Aspect Anonymous class Lambda
this The anonymous class instance itself The enclosing class instance (lexical scope)
Target Any interface or class (including abstract) Functional interfaces only (one abstract method)
State, multiple methods Fields, several methods, initializers No fields of its own
Holds the outer Whenever it uses the outer (and always if Serializable) Only if the body uses this, a field or an instance method

The this difference is easiest to see by running it:

class Demo {
    void run() {
        Runnable anon = new Runnable() {
            public void run() { System.out.println(this.getClass().getName()); }   // Demo$1
        };
        Runnable lambda = () -> System.out.println(this.getClass().getName());     // Demo
        anon.run();
        lambda.run();
    }
}
Variable scope, compilation, instances, serialization and performance
Aspect Anonymous class Lambda
Variable scope New scope, may redeclare (shadow) outer names Same scope as the enclosing method; redeclaring a name is an error
Compilation A separate .class file (Outer$1.class) per declaration site The body becomes a private method of the enclosing class; the actual class is spun at runtime via invokedynamic + LambdaMetafactory
Instances A new object every time the expression runs A non-capturing lambda is typically reused as one instance (a HotSpot implementation detail, not specified); a capturing lambda creates a new object
Serialization Serializable if the supertype is, dragging the outer object along Only if the target type is Serializable ((Runnable & Serializable) () -> ...); the serialized form depends on compiler-generated method names, very brittle, avoid it

Performance: an anonymous class costs loading a separate class per declaration site; an application with thousands of them shows it in startup time and metaspace. A lambda costs one invokedynamic bootstrap the first time it runs, and is cheap afterwards. In normal business code the difference isn’t a reason to choose; choose by semantics.

4. When to use records and sealed interfaces instead of nested classes or enums

Key idea: many nested classes in older code are just “bags of data” (private final fields, a constructor, getters, equals/hashCode). Since Java 16, that’s the job of a record.

public class PricingService {
    // Replaces a 30-line static nested class
    record Quote(String sku, BigDecimal unitPrice, int quantity) {
        Quote {
            if (quantity <= 0) throw new IllegalArgumentException("quantity must be > 0");
        }
        BigDecimal total() { return unitPrice.multiply(BigDecimal.valueOf(quantity)); }
    }
}
You need Use
Immutable data compared by value a record (nested if only this class uses it, or a local record)
A fixed set of values with the same shape an enum
A fixed set of cases, each carrying its own data a sealed interface + records
A stateful object with behavior, independent of any outer instance a static nested class (or top-level if widely used)
A helper tightly bound to one outer instance (iterator, view) an inner class
A function passed once a lambda or method reference

Exercises

1. Lab 07: all four nested classes in one order (and what to fix)

Task (paraphrased): an Order class has an id and a status. In its processing method, use a local class to log; an inner class holds the customer’s name and phone and prints them along with the order status; a static nested class computes a discount by status (10% when shipped, 0% when delivered/cancelled, 5% otherwise); and in main, an anonymous Runnable prints which status the order is being processed in. The status enum has a Vietnamese description and a method telling whether the status is final (delivered or cancelled).

Lab 07 solution and a real-code review

A single file you can run with java Lab07.java. The end of main adds two extra lines to show the outer.new Inner() syntax from outside and the discount for every status.

import java.math.BigDecimal;

public class Lab07 {
    enum OrderStatus {
        PENDING("Chờ xác nhận"),
        SHIPPED("Đang giao hàng"),
        DELIVERED("Đã giao"),
        CANCELLED("Đã huỷ");

        private final String label;

        OrderStatus(String label) { this.label = label; }

        String label() { return label; }

        boolean isFinal() { return this == DELIVERED || this == CANCELLED; }
    }

    static class Order {
        private final String id;
        private OrderStatus status;
        private final CustomerInfo customer;

        Order(String id, OrderStatus status, String name, String phone) {
            this.id = id;
            this.status = status;
            this.customer = new CustomerInfo(name, phone);   // inside the outer, no this.new needed
        }

        class CustomerInfo {                                   // inner: reads the outer's status
            private final String name;
            private final String phone;
            CustomerInfo(String name, String phone) { this.name = name; this.phone = phone; }
            void printInfo() {
                System.out.println("Customer: " + name + " - " + phone + " | order status: " + status.label());
            }
        }

        static class DiscountHelper {                          // static nested: no outer needed
            private DiscountHelper() {}
            static BigDecimal discountRate(OrderStatus status) {
                return switch (status) {
                    case SHIPPED -> new BigDecimal("0.10");
                    case DELIVERED, CANCELLED -> BigDecimal.ZERO;
                    case PENDING -> new BigDecimal("0.05");
                };
            }
        }

        void process() {
            class Logger {                                     // local class: reads the outer's id
                void log(String message) { System.out.println("[LOG] order " + id + " - " + message); }
            }
            Logger logger = new Logger();
            logger.log("start processing, status: " + status.label());
            customer.printInfo();
            System.out.println("Discount: "
                + DiscountHelper.discountRate(status).movePointRight(2).stripTrailingZeros().toPlainString() + "%");
            System.out.println("Final status: " + status.isFinal());
        }

        String id() { return id; }
        OrderStatus status() { return status; }
    }

    public static void main(String[] args) {
        Order order = new Order("A001", OrderStatus.PENDING, "Lan", "0900000000");
        order.process();

        Runnable task = new Runnable() {                       // anonymous class
            @Override
            public void run() {
                System.out.println("Order " + order.id() + " is being processed in status: " + order.status().label());
            }
        };
        task.run();

        Order.CustomerInfo other = order.new CustomerInfo("Minh", "0911111111");   // creating an inner object from outside: outer.new
        other.printInfo();
        for (OrderStatus s : OrderStatus.values()) {
            System.out.println(s + " -> " + Order.DiscountHelper.discountRate(s));
        }
    }
}
[LOG] order A001 - start processing, status: Chờ xác nhận
Customer: Lan - 0900000000 | order status: Chờ xác nhận
Discount: 5%
Final status: false
Order A001 is being processed in status: Chờ xác nhận
Customer: Minh - 0911111111 | order status: Chờ xác nhận
PENDING -> 0.05
SHIPPED -> 0.10
DELIVERED -> 0
CANCELLED -> 0

It works, but it’s a syntax exercise. Reviewing it as real code, I’d change:

  • The discount rate is a property of the status, so it belongs in the enum (SHIPPED("Đang giao hàng", new BigDecimal("0.10"))) rather than a helper class with a switch. The exhaustive switch at least catches a missing constant at build time; an if chain with an else returning 5% wouldn’t. Use BigDecimal, not double, for money.
  • CustomerInfo doesn’t need the order status: a customer is immutable data, so it should be record CustomerInfo(String name, String phone); printing it with the status is Order’s job. As an inner class, every CustomerInfo silently holds an Order.
  • The local Logger class should be a real logger (SLF4J) in a private static final field.
  • The anonymous Runnable becomes a lambda: Runnable task = () -> System.out.println(...);. order is effectively final, so it can be captured.

2. A builder as a static nested class, with validation

Task: write an immutable class describing an HTTP call (url required, method defaulting to GET, headers, timeout defaulting to 5 seconds) with a builder; the builder must reject non-positive timeouts and GET requests that declare a Content-Type.

Exercise 2 solution: validation in the setters and in build()

Take HttpCall from section 1.1 and add validation to the builder. Check individual parameters in the setters (fail early and clearly), and cross-field constraints in build().

public Builder timeout(Duration timeout) {
    if (timeout.isNegative() || timeout.isZero()) throw new IllegalArgumentException("timeout must be > 0");
    this.timeout = timeout;
    return this;
}

public HttpCall build() {
    if (method.equals("GET") && headers.containsKey("Content-Type")) {
        throw new IllegalStateException("GET request should not declare a body type");
    }
    return new HttpCall(this);
}

Why static: the builder exists before any HttpCall, so there can’t be an outer instance. The HttpCall(Builder) constructor is private, callable only from the builder (nested classes can access the outer’s private members). Map.copyOf in the constructor ensures that modifying the builder after build() doesn’t change the object already built.

3. Find and fix the memory leak

Task: a report job holds a large buffer and registers an inner-class listener on a static event bus to count events. After a few hours, the service dies with OutOfMemoryError. Explain and fix it.

Exercise 3 solution: a static nested listener and an unsubscribe handle

The inner class OnPriceChanged uses the outer’s handled field, so it has a this$0 pointing at ReportJob. The static event bus keeps listeners forever, so no ReportJob (with its 50 MB buffer) is ever collected. Switching to the lambda e -> handled++ doesn’t help, since that lambda still captures this. Fix it at two levels: the listener must not hold the outer object, and it must always be unsubscribed.

static final class EventBus {
    private static final List<Consumer<String>> LISTENERS = new CopyOnWriteArrayList<>();

    static Runnable subscribe(Consumer<String> listener) {
        LISTENERS.add(listener);
        return () -> LISTENERS.remove(listener);           // hand back a way to unsubscribe
    }
}

static class ReportJob implements AutoCloseable {
    private final byte[] buffer = new byte[50 * 1024 * 1024];
    private final AtomicInteger handled = new AtomicInteger();
    private Runnable unsubscribe;

    static final class OnPriceChanged implements Consumer<String> {   // static: no this$0
        private final AtomicInteger counter;
        OnPriceChanged(AtomicInteger counter) { this.counter = counter; }
        @Override public void accept(String event) { counter.incrementAndGet(); }
    }

    void start() { unsubscribe = EventBus.subscribe(new OnPriceChanged(handled)); }

    @Override
    public void close() { if (unsubscribe != null) unsubscribe.run(); }
}

try (ReportJob job = new ReportJob()) {
    job.start();
    // ...
}

I ran the broken version with -Xmx512m: 100 jobs lead to OutOfMemoryError. The fixed version only retains the small listener and the AtomicInteger; the buffers get collected. In practice you find this kind of bug with a heap dump (jcmd <pid> GC.heap_dump) and by looking at the “path to GC roots” of the retained object in Eclipse MAT or IntelliJ.

Remember

  • Explain why static nested is the default, and why a builder must be static.
  • Point out the retention path static field -> listener -> this$0 -> outer and the two fixes.
  • Explain why locals used in a lambda must be effectively final while fields need not be.
  • Know what this refers to in a lambda versus an anonymous class, and when you still need an anonymous class.
  • Know when to replace a nested class with a record or a sealed interface + records.

Interview questions

Junior

What’s the difference between a static nested class and an inner class?

A static nested class isn’t tied to any outer instance; an inner class is tied to one and keeps a hidden reference to it.

You create a static nested class with new Outer.Nested() and it can only use the outer’s static members. You create an inner class with outer.new Inner() and it can use all of the outer’s fields. Default to static nested and only use inner when you really need the outer’s state.

How do you create an inner-class object from outside the outer class? How does a local class differ from an anonymous class?

From outside you need an outer object: order.new CustomerInfo(...). A local class is named and reusable; an anonymous class is unnamed and used once.

Inside an instance method of the outer class, plain new CustomerInfo(...) works (an implicit this.new). A local class is declared inside a method, has constructors and can be reused several times in that method. An anonymous class is declared and instantiated in one expression, has no constructor of its own (it uses an instance initializer), and either extends one class or implements one interface.

Mid

What does this refer to inside a lambda versus inside an anonymous class?

In an anonymous class, this is the anonymous object itself; in a lambda, this is the enclosing class instance.

A lambda doesn’t introduce a new scope (which is also why it can’t redeclare a local variable name from outside). In practice: if a handler needs to unsubscribe itself with unsubscribe(this), you need an anonymous class; and toString() called inside a lambda is the enclosing class’s.

Why must local variables used in a lambda be effectively final?

Because the lambda gets a copy of the variable’s value, not the variable; allowing reassignment would make the copy and the original diverge.

A lambda may run after the method has returned, or on another thread, while locals live on the method’s stack. Java forbids reassignment to avoid divergence and race conditions. Fields aren’t restricted because the lambda captures this. The one-element-array workaround compiles but is usually bad design; with streams, use reduce or collectors.

Why is a builder usually a static nested class?

Because a builder exists before the object it builds, so there’s no outer instance to attach it to.

As an inner class you’d need an existing object just to create the builder, which makes no sense. As a nested class it can call the outer’s private constructor, so only the builder can create objects and every validation goes through it. It lives in the outer’s namespace (HttpCall.Builder), and being static it holds no hidden reference to any object.

Senior

Describe a backend scenario where an inner class or lambda leaks memory, and how you’d find it.

An inner-class or field-using lambda listener registered on a static event bus or executor and never removed pins a large outer object forever. Find it with a heap dump and the path to GC roots.

  • Scenario: a report-processing object holding a lot of data registers a listener on a static event bus, or schedules it on a periodic executor without cancelling it. The listener holds this$0 or this, so the large object is never collected.
  • Symptom: heap usage after each full GC creeps up until an OOM.
  • Find it: take a heap dump, look at the dominator tree and the path to GC roots, and you’ll see static field -> listener -> this$0 -> large object.
  • Fix: make the listener a static nested class that holds only what it needs, always unsubscribe (return an AutoCloseable handle), or use weak references where appropriate.

Useful phrases for interviews

  • “I default to a static nested class; an inner class keeps an implicit reference to the enclosing instance, which can leak memory.”
  • “The heap dump showed the path to GC roots going through this$0, so the listener was keeping the whole job alive.”
  • “Inside a lambda, this refers to the enclosing instance, whereas in an anonymous class it’s the anonymous object itself.”
  • “Captured locals must be effectively final because the lambda gets a copy of the value, not the variable.”
  • “A builder has to be a static nested class, because no outer instance exists yet when you use it.”
  • “From outside, you create an inner object with outer.new Inner(), which shows it can’t exist without the outer one.”
  • “I’d only reach for an anonymous class when I need state, several methods, or to extend an abstract class.”
  • “Double brace initialization creates an anonymous subclass, so I use Map.of instead.”

Notes based on the Hỏi Dân IT Java Core material plus my own research, rewritten in my own words.