Nested and Inner Classes in Java
Java lets you declare a class inside another class, and there are four kinds: static nested classes, inner classes, local classes and anonymous classes. They differ in one important way, whether each object is tied to an instance of the outer class, and that hidden link is behind both their convenience and a classic memory leak. This page shows all four, what the compiler generates, how to avoid the leak, and where lambdas and records now fit better.
Contents
Four kinds of nested class
A class declared inside another class is a nested class. Nesting is useful when a class only makes sense together with its outer class, such as an iterator for a collection or a builder for an object, and it lets the two share private members. The four kinds differ in where they are declared and whether they are linked to an instance of the outer class:
| Kind | Declared | Linked to an outer instance? | Typical use |
|---|---|---|---|
| Static nested class | In the class body, with static | No | Helpers, builders, keys, nodes of a data structure |
| Inner class | In the class body, without static | Yes, always | Iterators and views that read the outer object's state |
| Local class | Inside a method | Yes, if declared in an instance method | A small named helper used in one method |
| Anonymous class | In an expression, with new Type() { ... } | Yes, if created in an instance method | One-off implementations; mostly replaced by lambdas |
Nested records, enums and interfaces are always static, whether or not the keyword is written. When in doubt, make a nested class static
All four kinds in one program
The program uses each kind for a job it suits: a static PairCursorRunnable
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class FourKinds {
private final List<String> items = new ArrayList<>(List.of("b", "a", "c"));
// 1. Static nested class: no link to an outer instance
static class Pair {
final String left;
final String right;
Pair(String left, String right) {
this.left = left;
this.right = right;
}
}
// 2. Inner class: each instance belongs to an outer instance and can use its fields
class Cursor implements Iterator<String> {
private int pos;
@Override
public boolean hasNext() {
return pos < items.size(); // FourKinds.this.items
}
@Override
public String next() {
return items.get(pos++);
}
}
List<String> sortedCopy() {
// 3. Local class: declared inside a method, visible only there
class ByLength implements Comparator<String> {
@Override
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
}
List<String> copy = new ArrayList<>(items);
copy.sort(new ByLength().thenComparing(Comparator.naturalOrder()));
return copy;
}
public static void main(String[] args) {
Pair p = new Pair("x", "y"); // no outer object needed
System.out.println("pair: " + p.left + p.right);
FourKinds outer = new FourKinds();
Cursor c = outer.new Cursor(); // needs an outer object
StringBuilder sb = new StringBuilder();
while (c.hasNext()) {
sb.append(c.next());
}
System.out.println("inner cursor: " + sb);
System.out.println("local class sort: " + outer.sortedCopy());
// 4. Anonymous class: a one-off implementation, declared and created at once
Runnable task = new Runnable() {
private int runs;
@Override
public void run() {
runs++;
System.out.println("anonymous run #" + runs);
}
};
task.run();
task.run();
System.out.println("class files: " + Pair.class.getName() + ", "
+ Cursor.class.getName() + ", " + task.getClass().getName());
}
}
Output:
pair: xy
inner cursor: bac
local class sort: [a, b, c]
anonymous run #1
anonymous run #2
class files: FourKinds$Pair, FourKinds$Cursor, FourKinds$1
needed no outer object.new Pair(...) did: it is created withCursor , and itsouter.new Cursor() means the list of that particular outer object, so it printed "bac", the list in its original order.items- The local class
exists only insideByLength . Since all three items have length 1, thesortedCopy fallback sorted them alphabetically.thenComparing - The anonymous class kept state in a field,
, across two calls. That is one thing a lambda cannot do, because lambdas have no fields.runs - Every nested class compiles to its own
file named after its outer class:.class ,FourKinds$Pair , andFourKinds$Cursor for the first anonymous class. These names appear in stack traces.FourKinds$1
Shadowing, Outer.this and static members
An inner class can see three variables with the same name at once: a parameter, its own field, and the outer class's field. The program shows how to reach each one, that the inner class reads the outer's private fields, and two rules that changed in Java 16.
import java.lang.reflect.Modifier;
public class ShadowingAndStatics {
private String name = "outer field";
private static int created;
class Inner {
private String name = "inner field";
static int innerCount; // allowed in inner classes since Java 16
String names(String name) {
innerCount++;
return "parameter: " + name
+ " | this.name: " + this.name
+ " | ShadowingAndStatics.this.name: " + ShadowingAndStatics.this.name;
}
}
// Nested records, enums and interfaces are implicitly static
record Point(int x, int y) { }
enum Color { RED, GREEN }
ShadowingAndStatics() {
created++;
}
public static void main(String[] args) {
ShadowingAndStatics outer = new ShadowingAndStatics();
Inner inner = outer.new Inner();
System.out.println(inner.names("argument"));
// The inner class reads and writes the outer's private fields directly
System.out.println("private outer field readable from Inner: "
+ outer.new Inner().names("x").contains("outer field"));
System.out.println("Inner.innerCount = " + Inner.innerCount + ", created = " + created);
Point p = new Point(1, 2); // no outer instance needed
System.out.println(p + " " + Color.GREEN + ", Point is static: "
+ Modifier.isStatic(Point.class.getModifiers()));
}
}
Output:
parameter: argument | this.name: inner field | ShadowingAndStatics.this.name: outer field
private outer field readable from Inner: true
Inner.innerCount = 2, created = 1
Point[x=1, y=2] GREEN, Point is static: true
- A plain
means the nearest declaration, the parameter.name means the inner object's field, andthis.name (the qualifiedShadowingAndStatics.this.name ) means the outer object's field.this - The inner class read the outer's
field without any accessor: nested classes share private access with their outer class (they areprivatenestmates ). - Before Java 16, inner classes could not declare static members. JEP 395, which finalized records, lifted that restriction, so
is allowed and counted both inner objects.static int innerCount - The nested record
is static even though the keyword was not written, so it was created without an outer instance.Point
A common use: the builder pattern
A static nested Builderjava.net.http.HttpRequest
import java.util.ArrayList;
import java.util.List;
public class BuilderPattern {
// An immutable class built step by step by its static nested Builder
static final class HttpRequest {
private final String method;
private final String url;
private final List<String> headers;
private final int timeoutSeconds;
private HttpRequest(Builder b) { // only the Builder can call this
this.method = b.method;
this.url = b.url;
this.headers = List.copyOf(b.headers);
this.timeoutSeconds = b.timeoutSeconds;
}
static Builder newBuilder(String url) {
return new Builder(url);
}
@Override
public String toString() {
return method + " " + url + " " + headers + " timeout=" + timeoutSeconds + "s";
}
static final class Builder {
private final String url;
private String method = "GET";
private final List<String> headers = new ArrayList<>();
private int timeoutSeconds = 30;
private Builder(String url) {
this.url = url;
}
Builder method(String m) {
this.method = m;
return this; // returning this allows chaining
}
Builder header(String name, String value) {
headers.add(name + ": " + value);
return this;
}
Builder timeout(int seconds) {
if (seconds <= 0) {
throw new IllegalArgumentException("timeout must be positive");
}
this.timeoutSeconds = seconds;
return this;
}
HttpRequest build() {
return new HttpRequest(this);
}
}
}
public static void main(String[] args) {
HttpRequest get = HttpRequest.newBuilder("https://example.com/items").build();
HttpRequest post = HttpRequest.newBuilder("https://example.com/items")
.method("POST")
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.timeout(5)
.build();
System.out.println(get);
System.out.println(post);
}
}
Output:
GET https://example.com/items [] timeout=30s
POST https://example.com/items [Content-Type: application/json, Accept: application/json] timeout=5s
- The builder is
: it exists before anystatic does, so it must not be tied to one.HttpRequest 's constructor is private and takes the builder; because the builder is nested, it can call that constructor and the request can read the builder's private fields. Nothing else can create a request.HttpRequest- Each setter returns
, which allows the chained style. The first request used every default: GET, no headers, 30 seconds.this - Validation can happen in the setters (a non-positive timeout is rejected) or in
, and the finished object is immutable; seebuild()immutability .
Inner classes as live views, and local records
Two more patterns show where nested types fit best. An inner class makes a natural view: an object that stores nothing itself and shows part of its outer object, the way Map.keySet()List.subList()
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class LocalRecordsAndViews {
private final List<Integer> scores = new ArrayList<>(List.of(72, 95, 58, 88));
// An inner class used as a live VIEW: it stores nothing, it reads the outer list
class PassingView extends AbstractList<Integer> {
@Override
public Integer get(int index) {
return scores.stream().filter(s -> s >= 60).toList().get(index);
}
@Override
public int size() {
return (int) scores.stream().filter(s -> s >= 60).count();
}
}
static String report(Map<String, Integer> sales) {
// A local record (Java 16): a named tuple that exists only in this method
record Line(String region, int amount, double share) { }
int total = sales.values().stream().mapToInt(Integer::intValue).sum();
List<Line> lines = sales.entrySet().stream()
.map(e -> new Line(e.getKey(), e.getValue(), 100.0 * e.getValue() / total))
.sorted(Comparator.comparingInt(Line::amount).reversed())
.toList();
return lines.stream()
.map(l -> String.format("%-5s %4d %5.1f%%", l.region(), l.amount(), l.share()))
.collect(Collectors.joining("\n"));
}
public static void main(String[] args) {
LocalRecordsAndViews outer = new LocalRecordsAndViews();
List<Integer> passing = outer.new PassingView();
System.out.println("passing scores: " + passing);
outer.scores.add(61); // change the outer object...
System.out.println("after adding 61: " + passing); // ...and the view shows it
System.out.println(report(Map.of("north", 120, "south", 300, "east", 80)));
}
}
Output:
passing scores: [72, 95, 88]
after adding 61: [72, 95, 88, 61]
south 300 60.0%
north 120 24.0%
east 80 16.0%
is an inner class, so it reads thePassingView list of the object that created it. After 61 was added to the outer list, the same view object showed it. A static nested class would have needed the list passed in explicitly, which is better when the link is not meant to be live.scores- Views like this are cheap to create but recompute on every access; this one filters the whole list in every
, which is fine for small lists and slow for large ones. JDK views such asget are designed so that each access is cheap.keySet() is declared insiderecord Line and invisible outside it. It replaces the arrays orreport objects often used to carry several values through a stream, and its fields have names (Map.Entry ,region ,amount ), which makes the sorting and formatting code readable.share- Local records, enums and interfaces are implicitly static, so unlike local classes they cannot capture local variables or the outer instance. That keeps them simple values.
Anonymous classes compared with lambdas
Since Java 8, most anonymous classes that implement a single-method interface are written as lambdas. They look interchangeable, but thisnamethis.name
import java.util.function.Supplier;
public class LambdaVsAnonymous {
private final String name = "outer";
void compare() {
Supplier<String> anon = new Supplier<>() {
private final String name = "anonymous";
@Override
public String get() {
return "this.name = " + this.name; // this = the anonymous object
}
};
Supplier<String> lambda = () -> "this.name = " + this.name; // this = outer object
System.out.println("anonymous class: " + anon.get());
System.out.println("lambda: " + lambda.get());
}
public static void main(String[] args) {
new LambdaVsAnonymous().compare();
// Captured locals must be effectively final in both
int base = 10;
Supplier<Integer> s = () -> base + 1;
System.out.println("captured: " + s.get());
}
}
Output:
anonymous class: this.name = anonymous
lambda: this.name = outer
captured: 11
- Inside the anonymous class,
is the anonymous object, so it read "anonymous". Inside the lambda,this is the enclosing object, so it read "outer". A lambda is not a new scope forthis or for variable names.this - Both can capture local variables only if they are effectively final; see
final . - A lambda captures the outer instance only when its body uses
or an instance member, while inner and anonymous classes compiled by JDK 17 or earlier always captured it. Lambdas also do not create a separatethis file at compile time; they are linked at run time with.class .invokedynamic
| Need | Use |
|---|---|
| Implement a functional interface (one abstract method) | A lambda or method reference |
| Implement an interface with several methods, or extend a class | An anonymous class, or a named class |
| Keep state between calls | An anonymous or named class with fields |
this | An anonymous class |
Which kind to use
| Situation | Use |
|---|---|
| A helper type that belongs with the outer class | Static nested class (or a nested record or enum) |
| An object that reads or changes one outer object's state, such as an iterator | Inner class, created by the outer object itself |
| A small named class needed in only one method | Local class (or a local record, Java 16) |
| A one-off implementation of a single-method interface | A lambda |
| A one-off implementation of a larger interface or abstract class | Anonymous class |
| Anything stored long-term, such as listeners and cached callbacks | Static nested class or lambda, to avoid holding the outer object |