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:

The four kinds of nested class
KindDeclaredLinked to an outer instance?Typical use
Static nested classIn the class body, with staticNoHelpers, builders, keys, nodes of a data structure
Inner classIn the class body, without staticYes, alwaysIterators and views that read the outer object's state
Local classInside a methodYes, if declared in an instance methodA small named helper used in one method
Anonymous classIn an expression, with new Type() { ... }Yes, if created in an instance methodOne-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: it is simpler and cannot cause the leak described below.

All four kinds in one program

The program uses each kind for a job it suits: a static Pair, an inner Cursor that walks the outer object's list, a local comparator used only by one method, and an anonymous Runnable with its own counter. It ends by printing the names the compiler gave each class.

Java
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:

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
  • new Pair(...) needed no outer object. Cursor did: it is created with outer.new Cursor(), and its items means the list of that particular outer object, so it printed "bac", the list in its original order.
  • The local class ByLength exists only inside sortedCopy. Since all three items have length 1, the thenComparing fallback sorted them alphabetically.
  • The anonymous class kept state in a field, runs, across two calls. That is one thing a lambda cannot do, because lambdas have no fields.
  • Every nested class compiles to its own .class file named after its outer class: FourKinds$Pair, FourKinds$Cursor, and FourKinds$1 for the first anonymous class. These names appear in stack traces.

The hidden outer reference and memory leaks

An inner class instance needs its outer instance to read the outer fields, so the compiler adds a hidden field to it, named this$0. As long as the inner object is alive, so is the outer one. The program gives each outer object a 10 MB array, keeps only an inner object, and asks the garbage collector whether the outer object could be freed. It runs with the Serial collector so the result is repeatable.

Java
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;

public class OuterReference {

    private final byte[] bigData = new byte[10000000];   // 10 MB held by each outer object

    class UsesOuter {
        int size() {
            return bigData.length;                         // reads the outer instance
        }
    }

    class IgnoresOuter {
        int answer() {
            return 42;                                     // never touches the outer instance
        }
    }

    static class Nested {
        int answer() {
            return 42;
        }
    }

    static String fields(Class<?> c) {
        StringBuilder sb = new StringBuilder();
        for (Field f : c.getDeclaredFields()) {
            sb.append(f.getName()).append(f.isSynthetic() ? " (synthetic)" : "");
        }
        return sb.length() == 0 ? "none" : sb.toString();
    }

    // Keeps only the inner object, then checks whether the outer object was collected
    static boolean outerCollected(boolean useOuter) {
        OuterReference outer = new OuterReference();
        WeakReference<OuterReference> watch = new WeakReference<>(outer);
        Object keep = useOuter ? outer.new UsesOuter() : outer.new IgnoresOuter();
        outer = null;
        for (int i = 0; i < 5 && watch.get() != null; i++) {
            System.gc();
        }
        boolean collected = watch.get() == null;
        System.out.println("  still holding " + keep.getClass().getSimpleName());
        return collected;
    }

    public static void main(String[] args) {
        System.out.println("UsesOuter fields:    " + fields(UsesOuter.class));
        System.out.println("IgnoresOuter fields: " + fields(IgnoresOuter.class));
        System.out.println("Nested fields:       " + fields(Nested.class));

        System.out.println("outer collected while UsesOuter is alive: " + outerCollected(true));
        System.out.println("outer collected while IgnoresOuter is alive: " + outerCollected(false));
    }
}

Output:

Output
UsesOuter fields:    this$0 (synthetic)
IgnoresOuter fields: none
Nested fields:       none
  still holding UsesOuter
outer collected while UsesOuter is alive: false
  still holding IgnoresOuter
outer collected while IgnoresOuter is alive: true
  • UsesOuter has the synthetic field this$0; the static Nested has none.
  • While a UsesOuter object was alive, its outer object, and its 10 MB array, could not be collected. This is the classic leak: an inner class object (a listener, a callback, a cached iterator) is stored somewhere long-lived and silently keeps a large outer object in memory.
  • IgnoresOuter never reads the outer instance, and since JDK 18 javac leaves out the this$0 field in that case (JDK-8271623), so the outer object was collected. Compiled with an older JDK, it would have leaked too.
  • The fix is to make the class static whenever it does not need the outer instance, and to pass any needed values to it explicitly.

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.

Java
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:

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 name means the nearest declaration, the parameter. this.name means the inner object's field, and ShadowingAndStatics.this.name (the qualified this) means the outer object's field.
  • The inner class read the outer's private field without any accessor: nested classes share private access with their outer class (they are nestmates).
  • Before Java 16, inner classes could not declare static members. JEP 395, which finalized records, lifted that restriction, so static int innerCount is allowed and counted both inner objects.
  • The nested record Point is static even though the keyword was not written, so it was created without an outer instance.

A common use: the builder pattern

A static nested Builder is the usual way to create an immutable object with many optional settings, as java.net.http.HttpRequest does. The program builds two requests, one with only the defaults and one with several settings chained together.

Java
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:

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 static: it exists before any HttpRequest 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.
  • Each setter returns this, which allows the chained style. The first request used every default: GET, no headers, 30 seconds.
  • Validation can happen in the setters (a non-positive timeout is rejected) or in build(), and the finished object is immutable; see 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() and List.subList() work. A local record (Java 16) gives a name to an intermediate result that only one method needs. The program builds a view of passing exam scores and a sales report with percentages.

Java
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:

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%
  • PassingView is an inner class, so it reads the scores 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.
  • Views like this are cheap to create but recompute on every access; this one filters the whole list in every get, which is fine for small lists and slow for large ones. JDK views such as keySet() are designed so that each access is cheap.
  • record Line is declared inside report and invisible outside it. It replaces the arrays or Map.Entry objects often used to carry several values through a stream, and its fields have names (region, amount, share), which makes the sorting and formatting code readable.
  • 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 this means different things in each. The program gives both an outer field and an anonymous-class field the name name and reads this.name in each.

Java
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:

Output
anonymous class: this.name = anonymous
lambda:          this.name = outer
captured: 11
  • Inside the anonymous class, this 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 for this or for variable names.
  • Both can capture local variables only if they are effectively final; see final.
  • A lambda captures the outer instance only when its body uses this or an instance member, while inner and anonymous classes compiled by JDK 17 or earlier always captured it. Lambdas also do not create a separate .class file at compile time; they are linked at run time with invokedynamic.
Anonymous class or lambda?
NeedUse
Implement a functional interface (one abstract method)A lambda or method reference
Implement an interface with several methods, or extend a classAn anonymous class, or a named class
Keep state between callsAn anonymous or named class with fields
this should refer to the implementation itselfAn anonymous class

Which kind to use

Choosing a nested class
SituationUse
A helper type that belongs with the outer classStatic nested class (or a nested record or enum)
An object that reads or changes one outer object's state, such as an iteratorInner class, created by the outer object itself
A small named class needed in only one methodLocal class (or a local record, Java 16)
A one-off implementation of a single-method interfaceA lambda
A one-off implementation of a larger interface or abstract classAnonymous class
Anything stored long-term, such as listeners and cached callbacksStatic nested class or lambda, to avoid holding the outer object