Lesson · Nested & Inner Classes
Nested and inner classes: four ways to live inside
17 min readNested & Inner Classes
A class inside a class can be static (the default), inner (bound to an owner object), local or anonymous (born inside a method). The difference that matters is the hidden reference to an outer instance, and the leak it can cause.
The helper type that needs a home
A Tree needs a Node, and Node means nothing outside the Tree. Declaring it inside gives both a namespace and access to private members:
class Tree { private Node root; static class Node { // lives inside Tree, belongs to the type Node left, right; int value; } } // outside, the type is spelled Tree.Node
Predict: what does the compiler produce on disk? A separate class file, Tree$Node.class, next to Tree.class. Nesting is a source-level arrangement: at runtime there are two ordinary classes, related by name, access and a possible hidden reference.
Four ways to live inside
The four kinds differ on one axis that matters: whether each instance carries a hidden reference to an outer object:
| Kind | Declared | Enclosing instance | Typical use |
|---|---|---|---|
| Static nested | static class Node | None | Helper types: nodes, builders, entries that do not need owner state |
| Member inner | class Handler | One, hidden (this$0) | Each instance serves one enclosing object and reaches its state |
| Local | inside a method body | One, plus captured locals | A one-off helper used by that method only |
| Anonymous | new Runnable() { ... } | Same as local, unnamed | A one-off implementation; lambdas replace it for single-method types |
Static is the safe default. It nests the name and gains access to the enclosing class's private members without binding any instance to any owner; you pay for this$0 only when an inner class genuinely works for one outer object.
Nesting board · four ways to live inside
pick a kindDeclaration
no: it has no owner instance to reach
Tree$Node.class
Helper types: nodes, builders, entries. The default choice.
The this$0 field name, the class-file names and the capture behaviour were verified by compiling and reflecting on the demo in this lesson.
The hidden reference, and the leak it causes
A member inner class instance remembers its owner in a synthetic field. The verified name is this$0, and it makes three things true:
- Inside the inner class, the outer object's fields are in scope directly;
Outer.this.valuenames the owner explicitly when a name is shadowed. - Creating one requires an owner:
outer.new Handler(), because the reference must be bound at construction. - The leak: the inner instance keeps the outer object reachable. An entry in a static collection, or a listener that outlives its screen, pins the whole owner in memory.
The leak is the reachability lesson wearing a new coat. A long-lived inner object is a GC root chain to its outer object; if the inner never dies, the outer never does. The fix is one keyword: static, when the outer state was never needed.
How they compile
The class-file story for each kind, verified by compiling the demo:
- Nested classes are separate files:
Outer$Node.class,Outer$Handler.class; the dollar sign is the nesting record, and reflection reads it back viagetEnclosingClass(). - Locals and anonymous classes are numbered:
Outer$1.class,Outer$2.class, in order of appearance in the source; renaming or reordering them changes numbers, which is why they are kept short-lived. - Captured locals become fields: an anonymous class reading a method's local stores it in a synthetic field on the generated class; the local must be effectively final (assigned once), verified by the compiler's refusal.
- `this$0` is a field like any other: because the owner is stored explicitly, serialising an inner class serialises the owner too, one classic reason 'make it static' appears in style guides.
Source-level nesting, runtime-level classes. Nothing about the JVM nests objects; the compiler wires outer references and captured values in, which is exactly why their cost and their leaks are so predictable.
The nesting playbook
Choosing a home for a class, in order:
- Could the type stand alone? Make it top-level; nesting for tidiness alone ages badly.
- Does it exist purely to serve one enclosing class and need its private access?
static classis the default answer. - Does each instance genuinely work for one outer object, reaching its state? Then a member inner class earns its hidden reference.
- Will any inner or anonymous instance outlive the moment that created it? Keep it static, or make sure the owner is meant to stay alive.
- Inside methods: local classes and anonymous classes are for one-offs; for single-method interfaces (Runnable, Comparator), a lambda is shorter and avoids the class file entirely.
Name, access, reference: pick the cheapest binding. Most nested types want only the name; a minority want the owner; the compiler charges this$0 for exactly the minority that asked.
Nesting is a source arrangement; class files and references are the reality
Static nested classes carry no owner, member inner classes store one in this$0, and local or anonymous classes also capture effectively-final locals into synthetic fields. Every kind compiles to its own Outer$... class file, and every hidden reference is a reachability edge: a long-lived inner keeps its outer alive.
Interview angles
Static nested class versus member inner class?+
A static nested class has no enclosing instance and is created with plain new; a member inner class carries a hidden reference to one specific outer object, reaches its fields, and is created as outer.new Inner().
The reference is a real field named this$0 (verified via reflection), so it costs memory and creates a reachability edge: the inner keeps the outer alive as long as the inner lives. When no owner state is needed, static is strictly better.
class Outer { static class Nested { } // new Outer.Nested() class Inner { } // outer.new Inner(), holds this$0 }
Common misconception: That nesting itself implies an outer reference. Only the non-static member kind binds one; static nested is a plain class with a longer name.
Follow-up: What syntax reaches the outer object's own this from inside the inner class?
How does an inner class cause a memory leak?+
Through reachability: the inner instance holds this$0, so as long as anything reachable holds the inner (a static list, an event registry), the outer object cannot be collected either.
The classic case: an anonymous listener registered somewhere long-lived captures its activity or screen; the screen is gone but its whole object graph stays reachable. The fixes are structural: make it static with explicit parameters, unregister on teardown, or use a lambda with no capture.
// in a long-lived registry: listeners.add(new Listener() { ... }); // the anonymous instance holds this$0 // the enclosing screen stays alive until the listener is removed
Common misconception: That the leak is a garbage collector problem. The collector is doing its job; the program kept a path alive. Deleting the path is the fix.
Follow-up: Which two structural changes remove the path?
What does 'effectively final' mean for captured locals?+
A local captured by a local or anonymous class (or a lambda) may never be reassigned after initialisation; the compiler stores its value in a synthetic field inside the generated class.
Capturing by value is what makes the closure safe: the class reads its own copy, not the method's variable, which may die long before. The compiler enforces it with a precise message about final or effectively final variables; verified in this lesson's compilation.
int captured = 5; Runnable r = new Runnable() { public void run() { System.out.println(captured); } }; // captured = 6; // error: must be final or effectively final
Common misconception: That captured variables are shared by reference as in some other languages. Java copies the value in; mutation after capture is refused at compile time.
Follow-up: What does the same rule mean for loop variables handed to lambdas?
How do the four kinds appear in the compiled output, and why care?+
As separate class files: Outer$Node.class, Outer$Inner.class, and numbered Outer$1.class for locals and anonymous classes; their order of appearance decides the numbers.
The names leak into stack traces, reflection and serialisation, and the synthetic fields represent real state (this$0, captured values). Stack traces full of $1 tell the story of a post-mortem someone will debug; sensible naming and smaller closures make those traces readable.
Outer.class Outer$Nested.class Outer$Inner.class Outer$1.class
Common misconception: That nested classes are a compile-time convenience with no runtime fingerprint. They are ordinary classes, with names that surface everywhere.
Follow-up: What naming signature do lambdas leave in stack traces by contrast?
Local and anonymous classes versus lambdas: what is the rule of thumb today?+
For a single-method interface (Runnable, Comparator, listeners of one method), use a lambda: shorter, still captures effectively-final locals, no class file of its own. Keep anonymous classes when the implementation needs multiple methods, its own fields, or a name it refers to itself by.
Anonymous classes still make sense for quick subclasses with state and for abstract classes (lambdas need functional interfaces). Local classes win when the helper needs a constructor or several methods and lives inside exactly one method.
Runnable lambda = () -> System.out.println("one method: lambda"); Runnable anonymous = new Runnable() { public void run() { ... } }; // still legal, longer
Common misconception: That anonymous classes are deprecated in favour of lambdas. They remain the right tool beyond one method; the overlap is exactly the single-method case.
Follow-up: Why can a lambda never be an abstract class's subclass?