- Prerequisites
- 4.1 Classes · 5.1 Encapsulation
- Covers
- Static nested classes · Member inner classes
- Related
- 8.2 Local Classes · 8.3 Anonymous Classes · Book 2 (memory leaks, heap analysis) · Book 5 (Builder pattern)
On this page
1Concept / Definition
A nested class is a class declared inside another class or interface. Java has two kinds of member-level nested classes: a static nested class, which is simply a class scoped inside another and has no link to any outer object, and a member inner class (non-static), each instance of which is bound to an instance of the enclosing class and can use its fields and methods directly. Local and anonymous classes (8.2, 8.3) are further kinds of inner class declared inside code.

2Why It Exists
Nesting expresses that a type belongs to, or only makes sense with, its enclosing class: Map.Entry, Order.Line, HttpClient.Builder. It keeps related code together, avoids polluting the package namespace, and allows the nested class to access the outer class's private members. Inner classes additionally let an object provide a view or helper tightly bound to one outer instance — the classic example being an iterator over a collection's internal array.
3Core Concepts
Static nested classes
A static nested class is declared with static inside another type. It behaves like a top-level class with a qualified name (Outer.Nested): it can be instantiated without any Outer object, it cannot refer to the outer class's instance members, and it can access the outer class's private static members and — given an instance — its private instance members. Records, enums and interfaces declared inside a class are implicitly static.
Typical uses: builders (Pizza.Builder), value types that belong to a class (Order.Line), nodes of data structures (LinkedList.Node), and implementation helpers kept private to their outer class.
Member inner classes
A member inner class is declared without static. Every instance is bound to an enclosing instance and, whenever the class uses it, holds a hidden reference to that instance, created as outer.new Inner() (or just new Inner() inside an instance method of Outer). Inside the inner class, the outer instance is available as Outer.this, and its fields and methods can be used as if they were the inner class's own.

That hidden reference has two consequences. It costs memory in every inner object, and — more importantly — it keeps the outer object reachable as long as the inner object is. If an inner object is handed to something long-lived (a static registry, a cache, a thread pool), the outer object and everything it references cannot be garbage-collected.

4How It Works Internally
The JVM has no special concept of nesting in its execution model: each nested class compiles to its own class file named with $. For an inner class, the compiler adds a synthetic final field (conventionally this$0) and an extra constructor parameter to receive the outer instance. Since JDK 18, javac leaves the field out when the inner class never uses the outer instance, unless the class is serialisable; the constructor still takes the outer instance, so outer.new Inner() is still required (Example 4).

Before Java 11, access to private members across nested classes required compiler-generated synthetic accessor methods (access$000). Since Java 11 (JEP 181), classes in the same nest are recognised by the JVM as nestmates and can access each other's private members directly.
5APIs / Features / Syntax
The table collects the syntax and the reflection API for member-level nested classes; local and anonymous classes follow in 8.2 and 8.3.
| Form | Meaning |
|---|---|
| static class Nested { } | Static nested class; every nested record, enum and interface is static too |
| class Inner { } | Member inner class: each instance is bound to an Outer object |
| new Outer.Nested() | Creates a static nested object; no Outer object is needed |
| outer.new Inner() | Creates an inner object bound to outer; inside Outer, plain new Inner() binds to this |
| Outer.this.field | The enclosing object from inside Inner; needed when a name is shadowed (Q8) |
| static members in an inner class | Allowed since Java 16 (JEP 395); before that only constants |
| getNestHost(), isNestmateOf(), getEnclosingClass(), isMemberClass() | Reflection over nesting (Example 4) |
6Practical Examples
Example 1 — A static nested builder
Problem. Build an immutable Pizza with optional parts, without a constructor for every combination of arguments.
public final class Pizza {
private final String size;
private final List<String> toppings;
private Pizza(Builder b) { // only the Builder can create
this.size = b.size;
this.toppings = List.copyOf(b.toppings);
}
public static final class Builder { // static nested
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("olives").build();Why it works. The builder must exist before any Pizza does, so it cannot be an inner class; as a static nested class it can still call the private constructor. List.copyOf keeps each pizza immutable even if the builder is reused.
Example 2 — Mini program: an inner-class listener leak, measured
Problem. Figure 3 shows how a registered inner listener keeps its outer object alive. This program reproduces it: ten screens of 1 MB each register a price listener with a long-lived bus and are then dropped. Five use an inner listener, five a static nested one. Weak references tell whether the garbage collector could reclaim each screen.
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListenerLeak {
interface PriceListener { void onPrice(String sku, long paise); }
static final List<PriceListener> BUS = new ArrayList<>(); // for ever
static class Screen { // inner listener
private final byte[] cache = new byte[1_000_000]; // 1 MB per screen
private long last;
class Updater implements PriceListener {
public void onPrice(String sku, long paise) { last = paise; }
}
void open() { BUS.add(new Updater()); }
}
static class SafeScreen { // static nested listener
private final byte[] cache = new byte[1_000_000];
private final View view = new View();
static final class View implements PriceListener {
volatile long last;
public void onPrice(String sku, long paise) { last = paise; }
}
void open() { BUS.add(view); }
}
public static void main(String[] args) throws InterruptedException {
List<WeakReference<Object>> inner = new ArrayList<>();
List<WeakReference<Object>> safe = new ArrayList<>();
for (int i = 0; i < 5; i++) { // open and "close" 10 screens
Screen s = new Screen();
s.open();
inner.add(new WeakReference<>(s));
SafeScreen t = new SafeScreen();
t.open();
safe.add(new WeakReference<>(t));
}
BUS.forEach(l -> l.onPrice("SKU-1", 999));
System.out.println("listeners registered: " + BUS.size());
System.out.println("screens still in memory after GC: inner "
+ alive(inner) + " of 5, static " + alive(safe) + " of 5");
System.out.println("Updater fields: " + fields(Screen.Updater.class));
System.out.println("View fields: " + fields(SafeScreen.View.class));
}
static long alive(List<WeakReference<Object>> refs)
throws InterruptedException {
for (int i = 0; i < 10; i++) { System.gc(); Thread.sleep(20); }
return refs.stream().filter(r -> r.get() != null).count();
}
static List<String> fields(Class<?> c) {
return Arrays.stream(c.getDeclaredFields())
.map(f -> f.getName() + ": " + f.getType().getSimpleName())
.toList();
}
}listeners registered: 10
screens still in memory after GC: inner 5 of 5, static 0 of 5
Updater fields: [this$0: Screen]
View fields: [last: long]Why it behaves this way. Updater writes last, a field of Screen, so javac gives it a this$0 field: the static bus references the listener, the listener the screen, and all five screens stay reachable with their caches. View is static and keeps its own last, so the SafeScreen objects are collected while their views stay registered. In a heap dump the leak is a path from BUS through this$0 (section 8).
Example 3 — A member inner class that needs its outer instance
Problem. Iterate over a playlist's internal array without exposing the array.
public class Playlist implements Iterable<Song> {
private final Song[] songs;
private int size;
// bound to this playlist
public Iterator<Song> iterator() { return new Cursor(); }
private class Cursor implements Iterator<Song> { // member inner class
private int index;
public boolean hasNext() { return index < size; } // reads outer field
public Song next() {
if (!hasNext()) throw new NoSuchElementException();
return songs[index++]; // Playlist.this.songs
}
}
}Why it works. Each Cursor reads songs and size of the playlist that created it, which is what an inner class is for. It is private and short-lived, so its reference to the playlist does no harm.
Example 4 — What javac generates for each kind
Problem. Section 4 describes synthetic fields, extra constructor parameters and nestmates. This program asks reflection what javac really produced for four nested classes.
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class WhatJavacGenerates {
private int secret = 42;
class UsesOuter { int peek() { return secret; } } // inner, uses outer
class IgnoresOuter { int one() { return 1; } } // inner, does not
class Saved implements Serializable { // inner, serialisable
private static final long serialVersionUID = 1L;
}
static class Nested { // static nested
int peek(WhatJavacGenerates o) { return o.secret; } // private access
}
public static void main(String[] args) {
Class<?>[] kinds = WhatJavacGenerates.class.getDeclaredClasses();
Arrays.sort(kinds, Comparator.comparing(Class::getName));
for (Class<?> c : kinds) {
List<String> hidden = Arrays.stream(c.getDeclaredFields())
.filter(Field::isSynthetic).map(Field::getName).toList();
List<String> params = Arrays.stream(c.getDeclaredConstructors()[0]
.getParameterTypes()).map(Class::getSimpleName).toList();
System.out.printf("%-12s synthetic fields %-9s constructor %s%n",
c.getSimpleName(), hidden.toString(), params);
}
Class<?> n = Nested.class;
System.out.println("nest host of Nested: "
+ n.getNestHost().getSimpleName()
+ ", nestmate: " + n.isNestmateOf(WhatJavacGenerates.class));
System.out.println("private read via nestmate: "
+ new Nested().peek(new WhatJavacGenerates()));
}
}IgnoresOuter synthetic fields [] constructor [WhatJavacGenerates]
Nested synthetic fields [] constructor []
Saved synthetic fields [this$0] constructor [WhatJavacGenerates]
UsesOuter synthetic fields [this$0] constructor [WhatJavacGenerates]
nest host of Nested: WhatJavacGenerates, nestmate: true
private read via nestmate: 42Why it behaves this way. Every inner class takes the outer instance as a constructor parameter. Only UsesOuter, which reads secret, and the serialisable Saved keep a this$0 field; javac 18 and later drop it from IgnoresOuter (older compilers always added it). Nested has neither, and reads the private secret directly because it is a nestmate.
Example 5 — An inner class as a live view
Problem. Give callers a "low stock" view of an inventory that is always up to date, without copying the stock map or exposing it.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class LiveView {
static final class Inventory {
private final Map<String, Integer> stock = new TreeMap<>();
void put(String sku, int qty) { stock.put(sku, qty); }
LowStock lowStock(int threshold) { return new LowStock(threshold); }
final class LowStock { // inner: a view of THIS inventory
private final int threshold;
LowStock(int threshold) { this.threshold = threshold; }
List<String> skus() {
List<String> out = new ArrayList<>();
stock.forEach((sku, qty) -> {
if (qty < threshold) out.add(sku);
});
return out;
}
}
}
public static void main(String[] args) {
Inventory shop = new Inventory();
shop.put("pen", 40);
shop.put("ink", 3);
Inventory.LowStock low = shop.lowStock(5);
System.out.println("low stock: " + low.skus());
shop.put("pad", 2); // changes are visible at once
shop.put("ink", 50);
System.out.println("low stock: " + low.skus());
}
}low stock: [ink]
low stock: [pad]Why it behaves this way. LowStock reads stock through its enclosing Inventory on every call, so the second call sees the changes. Map.keySet() works the same way.
7Common Problems & Mistakes
| Mistake | Consequence | Fix |
|---|---|---|
| Inner class where static would do | Extra reference per object; possible leaks, and a needless constructor parameter that ties every object to an outer one | Declare static (Figure 5) |
| Inner listener or task registered in a long-lived structure | Outer object (e.g. an Activity, a request context) leaked; the outer object keeps all its fields, often megabytes, alive as long as the registry lives (Example 2) | Static nested class holding only what it needs; unregister; weak references where appropriate |
| Serialising inner class instances | Outer instance serialised too, or failure: NotSerializableException when the outer class is not serialisable, or a much larger stream when it is | Static nested classes for serialisable types, and never rely on the outer object being written |
| Deeply nested classes | Hard to read and navigate: readers must track several levels of this and of scope | Promote to top-level package-private classes |
| Assuming javac 18+ removes every outer reference | Inner classes that use the outer object, or are serialisable, still hold this$0 | Make the class static rather than relying on the compiler |
| Builder declared as an inner class | new Pizza.Builder() does not compile without a Pizza, which does not exist yet | Declare builders static |
| A field of the inner class named like an outer field | x silently means the inner field; reading Outer.this.x was intended (Q8) | Rename one of them, or write Outer.this.x explicitly |
8Performance & Production Considerations
Inner-class leaks appear in heap dumps as unexpectedly retained outer objects, reachable through a this$0 field from a long-lived root such as a static collection, a thread-local or a scheduler. Heap analysers (Eclipse MAT, VisualVM, JFR's old-object sampling) show this path directly; recognising this$0 in a GC-root path is a useful diagnostic skill (Book 2).
- In Eclipse MAT, open the dominator tree for the class that is unexpectedly retained and use "Path to GC roots", excluding weak references: an inner-class leak shows as a chain through a field named
this$0.
9Architecture & Design Considerations
Nested classes are a tool for encapsulation at the smallest scale: a private static nested class is invisible outside its outer class, which is a tighter boundary than package-private. Use them for types that belong to exactly one class. Types used across the package or wider should be top-level, where they are easier to find and test.

10Interview Questions & Answers
What is the difference between a static nested class and an inner class?
A static nested class has no link to an outer instance and can be created on its own. An inner (non-static) class instance is bound to an outer instance, holds a hidden reference to it, and can access its instance members directly. With javac 18 and later, the field exists only if the inner class uses the outer object or is serialisable, but the binding to an outer instance remains.
How do you create an instance of a member inner class from outside the outer class?
With an outer instance: Outer outer = new Outer(); Outer.Inner in = outer.new Inner(); — the inner object is bound to that outer instance. Inside an instance method of Outer, plain new Inner() binds the new object to this.
Why is the Builder pattern usually implemented as a static nested class?
The builder must be created before any instance of the outer class exists, so it cannot be an inner class. Being nested lets it call the outer class's private constructor and keeps the two types together.
How can an inner class cause a memory leak?
Each inner instance holds a hidden reference to its outer instance. If the inner object is stored somewhere long-lived — a static list of listeners, a cache, a scheduled task — the outer object and everything it references stays reachable and cannot be collected. A heap dump shows the leak as a path through a this$0 field (Example 2); the fix is a static nested class or unregistering the object.
What are nestmates in Java 11?
A JVM-level recognition that a top-level class and its nested classes form a nest, recorded in NestHost and NestMembers attributes. Nestmates can access each other's private members directly, removing the synthetic accessor methods older compilers generated.
When would you use a nested class instead of a top-level class in a codebase?
When the type is meaningful only together with its enclosing class — a builder, an entry, an internal node or iterator — and ideally private. If it is used across the package or independently tested, a top-level class is clearer. Default to static unless the outer instance is really needed.
Which nested types are implicitly static?
Nested records, enums and interfaces, whether declared in a class or in an interface, and every class declared inside an interface. They can never be bound to an outer instance. Only classes declared in a class without static are inner classes.
What does this program print?
public class ShadowQuiz {
int x = 1;
class Inner {
int x = 2;
void show(int x) {
System.out.println(x + " " + this.x + " "
+ ShadowQuiz.this.x);
}
}
public static void main(String[] args) {
ShadowQuiz outer = new ShadowQuiz();
ShadowQuiz.Inner in = outer.new Inner();
outer.x = 10;
in.show(3);
}
}It prints 3 2 10. Inside show, the parameter x shadows the field, so plain x is 3. this.x is the inner class's own field, 2. ShadowQuiz.this.x reads the enclosing object's field, which was set to 10 after the inner object was created: the inner object holds a reference to the outer object, not a copy of its fields.
An inner class never touches its outer object. Does it still keep the outer object alive?
It depends on the compiler and the class. Since JDK 18, javac omits the this$0 field in that case, unless the class is serialisable, so the outer object can be collected (Example 4); class files compiled by older compilers always keep the field. Either way the constructor still requires an outer object. Declaring the class static removes the question and documents the intent.
What does javac generate for outer.new Inner()?
A class file Outer$Inner.class whose constructor takes the outer instance as an extra first parameter. At the call site javac null-checks outer (a NullPointerException here, not later) and passes it in; if the class uses the outer object, the constructor stores it in the synthetic field this$0. Outer and Outer$Inner record each other in the NestHost and NestMembers attributes, which lets them read each other's private members.
A service's heap grows until OutOfMemoryError. The heap dump shows 40,000 RequestContext objects, each retained through this$0 of a RetryTask held by a scheduler queue. What happened and how do you fix it?
RetryTask is an inner class of RequestContext and uses its fields, so every queued task keeps its whole request context alive, including request bodies, until the task runs or is cancelled; tasks that are never cancelled leak. Make RetryTask a static nested or top-level class that receives only the data it needs, cancel tasks when a request completes, and bound the queue. A heap-histogram alert on RequestContext catches a relapse.
Why does serialising an inner class instance fail with NotSerializableException, or produce a much larger stream than expected?
Serialisation writes the object's fields, and a serialisable inner class always keeps its this$0 field, so the outer object is written too. If the outer class is not serialisable, writing fails; if it is, its whole object graph goes into the stream.
A class has grown six nested classes. When do you move them to top-level classes?
Keep a nested class when it is meaningful only with its outer class, such as a builder or an entry. Move it to a package-private top-level class when it has its own logic worth testing, is used elsewhere in the package, or makes the file hard to read. Nesting gives tighter encapsulation; top-level classes are easier to find and test.
What rules would you set for nested types in the public API of a widely used library?
Nested types are part of the API and of the binary names (Client$Builder), so treat them like any public type: static unless they are views bound to an instance, final unless designed for extension, and stable in name. Expose Client.builder() rather than constructors, and enforce static-unless-needed with static analysis, so that a later edit cannot add a hidden outer reference to a long-lived type.
Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.
Key Takeaways
- Static nested: scoped inside another class, no outer instance.
- Member inner: bound to an outer instance via a hidden reference (Outer.this).
- The hidden reference costs memory and can leak the outer object — prefer static.
- Each nested class is its own class file; nestmates share private access since Java 11.