Inner Classes: Nested Logic

Inner Classes: Nested Logic in Java: Elm Court is a block of twenty-four flats. Twenty-three are let to tenants.

The Analogy: The Caretaker's Flat In A Block Of Flats

Elm Court is a block of twenty-four flats. Twenty-three are let to tenants. The twenty-fourth, on the ground floor beside the bin store, is the caretaker's flat. It is not a separate building and not on a separate deed: it appears on Elm Court's own floor plan, its address is a letter after Elm Court's number, and its entire reason for existing is the block it sits in. Nobody would build that flat on an empty field.

Because it is inside, the caretaker's flat comes with things no tenant gets. The caretaker holds keys to the riser cupboards, the meter room, the roof hatch and the pump room -- including every door marked private that a tenant may not open. He does not have to ask; the keys are part of the flat. The other side of that bargain is that the flat cannot be let on its own, because its plumbing, its stairs and its front door all belong to the block.

At the back of the site there are also six lock-up garages. They stand on the same deed as Elm Court but they open onto the service road and hold no keys to anything inside the block; a garage is useful to whoever rents it and completely indifferent to which flat that person lives in. And there are the temporary arrangements too: the scaffold gantry erected inside flat 12 for the week the ceiling is repaired, and the plywood jig the joiner cuts on the bench to hold one awkward sash while he glues it. The gantry has a name written on the permit; the jig has no name at all and is firewood by Friday.

Now the failure. The caretaker signs a twenty-five-year service agreement with the district heating company and gives his flat as the contact address. Years pass; the last tenant moves out, the block is emptied, the managing agent closes the file and everyone considers Elm Court finished with. It is not finished with, because a live contract in somebody else's filing cabinet still points at a flat inside it, and you cannot demolish a building that an active address refers to. That is exactly what a non-static inner class does to the object enclosing it, and it is the most expensive mistake in this lesson.


Syntax or Core Structure

A class declared inside another class comes in two member flavours. Without static it is an inner class and every instance of it is bolted to an instance of the enclosing class. With static it is a static nested class and it stands alone.

public class Building {
    private final String name;
    private int floors;
    private static int built = 0;

    public Building(String name, int floors) {
        this.name = name;
        this.floors = floors;
        built++;
    }

    // Inner class: cannot exist without a Building.
    class Caretaker {
        private final String name;              // shadows Building.name

        Caretaker(String name) {
            this.name = name;
        }

        String report() {
            // Building.this reaches past the shadow to the enclosing instance.
            return this.name + " looks after " + Building.this.name
                 + " (" + floors + " floors)";
        }

        void addFloor() {
            floors++;                           // writes the enclosing object's field
        }
    }

    // Static nested class: no enclosing instance, no access to floors or name.
    static class Garage {
        private final String bay;

        Garage(String bay) {
            this.bay = bay;
        }

        String label() {
            return "bay " + bay + " of " + built + " built";
        }
    }

    public static void main(String[] args) {
        Building elm = new Building("Elm Court", 4);
        Building oak = new Building("Oak Court", 9);

        Building.Caretaker iris = elm.new Caretaker("Iris");
        System.out.println("report    " + iris.report());

        iris.addFloor();
        System.out.println("floors    " + elm.floors);
        System.out.println("oak       " + oak.floors);

        Building.Garage g = new Building.Garage("G-3");
        System.out.println("garage    " + g.label());
        System.out.println("built     " + built);
    }
}

Output:

report    Iris looks after Elm Court (4 floors)
floors    5
oak       9
garage    bay G-3 of 2 built
built     2

Three things in that output are worth pausing on. report proves the inner class read a private field of another class, Building.name, with no getter involved. floors 5 beside oak 9 proves addFloor() mutated one specific enclosing object rather than some shared notion of "the building". And garage proves the static nested class could be built with a plain new and knew nothing about Elm Court at all.


Technical Depth: The Four Kinds Of Nested Class, The Hidden Reference One Of Them Carries, And What The Compiler Emits Behind Your Back

The four kinds, and the single question that separates them

Java has four nested-class forms, and people usually try to memorise them as a list. Do not. One question sorts all four: does an instance of this class need an instance of something else in order to exist? Everything else follows from the answer.

KindWhere you declare itNeeds an enclosing instanceSees enclosing instance fieldsWhat it is for
Static nestedA member of the outer class, marked staticNoNo -- only the outer class's static membersA helper type filed under its owner's name: a node, a builder, a result record
Inner (non-static member)A member of the outer class, no staticYesYes, including private onesA view of its owner that is meaningless alone: an iterator, an adapter, a live sub-list
LocalInside a method, constructor or initialiser blockOnly if that block is itself in an instance contextYes, plus enclosing locals that are effectively finalA named type that exactly one method needs
AnonymousInside an expression, as part of a newOnly if that expression is in an instance contextYes, plus enclosing locals that are effectively finalA one-off implementation you will never refer to by name

The word "inner" is not a loose synonym for "nested". In the specification, static member classes are not inner classes; Map.Entry is a static nested interface and ArrayList's iterator is a genuine inner class. Getting that vocabulary right saves a lot of confusion when you read an error message.

How you write new for each, and the error you get when you forget

A static nested class behaves exactly like a top-level class with a long name. An inner class needs a specific enclosing object, and the syntax puts that object in front of the new:

Building.Garage g = new Building.Garage("G-3");     // static nested: from anywhere
Garage g2 = new Garage("G-4");                      // static nested: from inside Building

Building elm = new Building("Elm Court", 4);
Building.Caretaker c = elm.new Caretaker("Iris");   // inner: elm is the enclosing instance

That elm.new form looks wrong the first time you see it, and it is the only place in the language where an expression appears to the left of new. Inside an instance method of Building you can drop it, because this silently supplies the enclosing instance and new Caretaker("Iris") means this.new Caretaker("Iris"). Inside a static method -- main, for instance -- the unqualified form does not compile, and the message is the one every Java programmer meets early:

error: non-static variable this cannot be referenced from a static context

That message is not about your variable. It is the compiler saying it has no enclosing instance to hand to the inner class's hidden constructor parameter. The two fixes are to supply one, or to decide the class never needed one and mark it static.

What each kind may and may not declare

The four forms are not equally capable, and the differences are not arbitrary -- each one falls out of whether the class has a name you can write down and whether it has an enclosing instance.

QuestionStatic nestedInnerLocalAnonymous
Can you write your own constructorYesYesYesNo -- you may only use an initialiser block
How many supertypes may it nameOne class plus any number of interfacesSameSameExactly one, the type after new
Can it be public, protected or privateYesYesNo -- its scope is the enclosing blockNo
Can it declare static methodsYesYes, on Java 16 and laterYes, on Java 16 and laterNo
Can it be abstractYesYesYesNo -- it is being instantiated
Can it be referred to by name laterYesYesOnly inside its own blockNo

The anonymous class's "exactly one supertype" limit is the one that bites in practice. The moment you want a second interface, a constructor that takes arguments, or a name in the stack trace, the anonymous form has run out and you should promote it. Since Java 8 a lambda is usually the better answer for the single-abstract-method case anyway, and a lambda does not capture the enclosing instance unless its body actually uses it -- a real behavioural difference, not a style preference.

Capture, part one: locals are copied, and that is why they must be effectively final

A local or anonymous class can read the locals and parameters of the method it sits in, but only the ones that are effectively final -- assigned exactly once and never reassigned. The reason is not fussiness: the class outlives the method call, so the compiler cannot read the variable later and instead copies its value into a synthetic field at construction time. If the variable could still change, the copy and the original would silently disagree, so the language forbids it.

public class Capture {

    interface Step {
        String run();
    }

    static Step localVersion(String site) {
        int pass = 2;
        // pass = 3;   // uncomment and Named stops compiling: pass is no longer effectively final
        class Named implements Step {
            public String run() {
                return site + " pass " + pass;
            }
        }
        return new Named();
    }

    static Step anonymousVersion(String site) {
        int pass = 7;
        return new Step() {
            public String run() {
                return site + " pass " + pass;
            }
        };
    }

    public static void main(String[] args) {
        System.out.println("local     " + localVersion("bay-1").run());
        System.out.println("anon      " + anonymousVersion("bay-2").run());
    }
}

Output:

local     bay-1 pass 2
anon      bay-2 pass 7

Both calls returned an object that still knows site and pass long after the method holding those variables returned and its stack frame was discarded. Nothing magical happened: the values were photographed on the way past.

Capture, part two: the enclosing instance is held by reference, and it keeps changing

Here is the distinction most tutorials skip. Captured locals are copied by value. The captured enclosing instance is held by reference, so the nested class sees every later change to its fields. Same syntax, opposite semantics.

public class Timing {

    interface Probe {
        int read();
    }

    private int stage = 1;

    Probe liveProbe() {                           // instance method: captures Timing.this
        return new Probe() {
            public int read() {
                return stage;                     // reads the field, now, on every call
            }
        };
    }

    static Probe frozenProbe(int stage) {         // static method: captures a local
        return new Probe() {
            public int read() {
                return stage;                     // reads a copy taken at construction
            }
        };
    }

    public static void main(String[] args) {
        Timing t = new Timing();
        Probe live = t.liveProbe();
        Probe frozen = frozenProbe(t.stage);

        t.stage = 9;

        System.out.println("live      " + live.read());
        System.out.println("frozen    " + frozen.read());
    }
}

Output:

live      9
frozen    1

Both probes were created while stage was 1. Both were asked after it became 9. The one that captured the object answered 9; the one that captured an int answered 1. If you have ever had a callback report a stale value, or report a surprisingly fresh one, this is almost always the reason.

What the compiler emits, and the names that turn up in your stack traces

Nested classes are a source-level convenience. The JVM has no concept of nesting at all, so javac flattens everything into ordinary class files with manufactured names:

  • Building$Caretaker.class and Building$Garage.class for the member classes. The binary name is the enclosing class's binary name, then $, then the simple name -- that part is specified, so you can rely on it.
  • Building$1Named.class for a local class and Building$1.class for an anonymous one. The digits are chosen by the compiler in declaration order and are explicitly not specified. Never write code, a config file or a log filter that depends on them.

For the inner class, flattening leaves a problem: Building.this has to become a real field access. So the compiler adds a synthetic final field, conventionally called this$0, and gives every constructor a hidden first parameter to fill it. Your elm.new Caretaker("Iris") really calls a two-argument constructor whose first argument is elm.

Three consequences follow directly from that hidden field, and all three are real:

  1. Every instance of an inner class costs one extra reference of memory, forever.
  2. Serializing an inner-class instance serializes the enclosing instance too, transitively -- and if the enclosing class is not serializable, the write fails at runtime.
  3. getSimpleName() returns the empty string for an anonymous class, and getDeclaringClass() is null for local and anonymous ones while getEnclosingClass() is not. Reflection-driven frameworks trip over this constantly.

Make it static by default, and what happens when you do not

The rule is short: if a member class does not need the enclosing instance, mark it static. Not marking it is not a neutral choice. Compare the two shapes:

class Log {
    private final int[] readings = new int[100_000];

    class Watcher implements Runnable {           // pins this Log, and its 100k ints
        public void run() { /* uses Log.this.readings */ }
    }
}

class Log2 {
    static class Watcher implements Runnable {    // pins nothing it was not given
        private final String site;
        Watcher(String site) { this.site = site; }
        public void run() { /* uses site only */ }
    }
}

Both compile, and both look equally tidy in review. But hand a Log.Watcher to a listener list, a thread pool or any static collection, and that collection now holds a live reference to a four-hundred-kilobyte Log for as long as it holds the watcher -- even though the watcher's own code may never touch readings. The garbage collector is behaving perfectly; the object really is reachable. This is the caretaker's twenty-five-year heating contract, and it is the classic cause of a heap that grows steadily and never comes back down.

The ways out, in order of preference: make the class static and pass it the two or three values it actually needs; if the callback genuinely must see live state, keep it inner but ensure the registry that holds it has a matching removal call you actually invoke; or, for caches you do not control, reach the enclosing object through a WeakReference and handle the null.


Real World Example: A Heating Meter Log Whose Iterator Is Rightly Inner, Whose Summary Is Rightly Static, And Whose Watcher Is Neither

Elm Court's heating meter is read eight times a season. The class below stores those readings, hands them out through an iterator, produces a summary for the managing agent, and lets the agent register a peak-usage watcher. Three nested classes, three different correct answers -- and one of them is wrong on purpose.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

public class ReadingLog implements Iterable<Integer> {

    private static final List<Runnable> WATCHERS = new ArrayList<>();
    private static final int CAPACITY = 8;

    private final String site;
    private final int[] kwh = new int[CAPACITY];
    private int count;
    private int rejected;

    public ReadingLog(String site) {
        this.site = site;
    }

    public boolean add(int reading) {
        if (reading < 0 || count == CAPACITY) {
            rejected++;
            return false;
        }
        kwh[count++] = reading;
        return true;
    }

    // INNER, and rightly so: it walks the enclosing array and index directly.
    private class Cursor implements Iterator<Integer> {
        private int at;

        public boolean hasNext() {
            return at < count;
        }

        public Integer next() {
            return kwh[at++];
        }
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Cursor();
    }

    // STATIC NESTED, and rightly so: it carries numbers out and needs nothing else.
    public static final class Summary {
        private final String site;
        private final int readings;
        private final int total;
        private final int peak;

        Summary(String site, int readings, int total, int peak) {
            this.site = site;
            this.readings = readings;
            this.total = total;
            this.peak = peak;
        }

        public int mean() {
            return readings == 0 ? 0 : total / readings;
        }

        @Override
        public String toString() {
            return String.format(Locale.ROOT,
                "%-8s n %2d  total %5d  peak %4d  mean %4d",
                site, readings, total, peak, mean());
        }
    }

    public Summary summary() {
        int total = 0;
        int peak = 0;
        for (int v : this) {                       // goes through Cursor
            total += v;
            if (v > peak) {
                peak = v;
            }
        }
        return new Summary(site, count, total, peak);
    }

    // THE FLAW: an anonymous inner class parked in a static list forever.
    public void watchForPeak(int limit) {
        WATCHERS.add(new Runnable() {              // captures ReadingLog.this
            @Override
            public void run() {
                int over = 0;
                for (int v : ReadingLog.this) {
                    if (v > limit) {
                        over++;
                    }
                }
                System.out.println(String.format(Locale.ROOT,
                    "%-8s over %2d of %2d", site, over, count));
            }
        });
    }

    public static int watchers() {
        return WATCHERS.size();
    }

    public static void main(String[] args) {
        ReadingLog elm = new ReadingLog("elm");
        int[] feed = { 210, 198, -4, 265, 240, 233, 251, 202, 219, 244 };
        for (int v : feed) {
            elm.add(v);
        }

        ReadingLog oak = new ReadingLog("oak");
        oak.add(140);
        oak.add(155);

        System.out.println(elm.summary());
        System.out.println(oak.summary());

        elm.watchForPeak(240);
        oak.watchForPeak(240);
        System.out.println("watchers  " + watchers());
        for (Runnable w : WATCHERS) {
            w.run();
        }

        System.out.println("rejected  " + elm.rejected);
        System.out.println("cursor    " + Cursor.class.getName());
        System.out.println("summary   " + Summary.class.getName());
    }
}

Output:

elm      n  8  total  1818  peak  265  mean  227
oak      n  2  total   295  peak  155  mean  147
watchers  2
elm      over  2 of  8
oak      over  0 of  2
rejected  2
cursor    ReadingLog$Cursor
summary   ReadingLog$Summary

Cursor earns its non-static status honestly. It reads kwh and count, two private fields of the log it belongs to, and there is no sensible way to construct one without a log. Making it static would mean passing the array and the count into its constructor, which would either copy them -- breaking the live view an iterator is supposed to give -- or hand out the internal array, which is worse than the inner class ever was. Note also that Cursor is private: callers receive it as an Iterator<Integer> and can never name the implementing type.

Summary earns its static just as honestly, and the two feed lines show why it matters. Elm's eight accepted readings total 1818 with a peak of 265; oak's two total 295 with a peak of 155. A Summary is something the managing agent may keep in a list for five years, e-mail, cache or serialize, and none of those uses should quietly retain a ReadingLog and its array. Marking it static and final with final fields makes it a value: it cannot change, and it cannot reach back.

The rejection count of 2 shows the guard working twice for different reasons -- -4 failed the sign check and 244 arrived when count had already reached CAPACITY. That second rejection means add silently drops good data once the season is full and reports it only through a return value main ignores. The over 2 of 8 line is subtler than it looks too: 265 and 251 exceed the 240 limit but 240 itself does not, because the test is v > limit and not v >= limit. Off-by-one in a threshold is not a nested-class problem, but it is exactly the sort of thing that hides inside a callback nobody reads.

Now the limits, and the flaw the class was built around. watchForPeak adds an anonymous inner Runnable to a private static final list, so WATCHERS holds elm and oak -- and their arrays -- for the lifetime of the JVM, with no removeWatcher anywhere in the class. Register a watcher per log in a long-running process and the heap grows without bound while every field involved looks innocent. The watcher compounds the error by printing to System.out from inside a callback, which makes it untestable and unusable on a server. Beyond that: Cursor.next() never throws NoSuchElementException as the Iterator contract requires, so an exhausted cursor produces an ArrayIndexOutOfBoundsException instead; Cursor keeps no modification count, so calling add mid-iteration silently changes what the loop sees rather than failing fast; Summary.mean() truncates, reporting elm's 227.25 as 227 in every report the agent files; kwh is a fixed int[CAPACITY], so a ninth reading can never be stored; and WATCHERS is a mutable static touched from instance methods, so two threads registering at once corrupt the ArrayList.


Common Mistakes

  1. Leaving a member class non-static out of habit. Node, Entry, Config and Result almost never need the enclosing instance, yet they are written without static constantly. Ask "does this class read a non-static member of the outer class?" -- if the answer is no, type static.
  2. Registering an inner-class instance in a long-lived collection and never removing it. An anonymous Runnable created inside an instance method looks like a closure over three integers and is actually a closure over the whole object. If there is an addListener, find the removeListener before you use it.
  3. Writing new Inner() from a static method and misreading the error. "non-static variable this cannot be referenced from a static context" is not about a variable you wrote; it means the inner class needs an enclosing instance the static method does not have. Supply one with outer.new Inner(), or mark the class static.
  4. Shadowing an outer field and then losing track of which one you wrote to. this.name is the inner one, Outer.this.name is the outer one, and plain name is whichever is nearest -- so assigning to plain name in a constructor whose parameter has that name updates nothing at all.
  5. Assuming a captured local tracks later changes. int total = 0; list.forEach(x -> total += x); does not compile, and the one-element-array workaround people reach for works only because the array reference is final while its contents are not. Locals are photographed at capture; only object state stays live.
  6. Reassigning a variable and breaking a class further down the method. Adding an innocent limit = limit * 2; above a local or anonymous class that reads limit stops the whole class compiling, with the error reported at the use rather than at the assignment you just added.
  7. Depending on Outer$1 in logs, filters or config. Those digits are assigned by the compiler in declaration order and are not specified. Insert one anonymous class earlier in the file and every later number shifts.
  8. Making a nested class public when it exists only to serve its owner. A public nested class is part of your API forever, name and all. Keep implementation types private and return them as the interface they implement, as ReadingLog.Cursor does.
  9. Reaching for an anonymous class where a lambda or a named class is clearly better. An anonymous class cannot take constructor arguments, cannot implement two interfaces, produces a nameless frame in stack traces, and captures the enclosing instance whether or not it uses it.

Best Practices

  • Default to static on every member class and remove it only when the compiler forces you to. This single habit prevents the entire class of retention bug described above, and it costs nothing -- you find out immediately when the class really needs its owner.
  • Use a genuine inner class for a live view of its owner: iterators, cursors, sub-lists, adapters. These are the cases where the coupling is the point. Declare them private and hand them out as an interface type.
  • Keep nested classes small. A nested class that grows past fifty lines or acquires its own collaborators is a top-level class that has not moved out yet. Nesting is for types too small to deserve a file.
  • Name the type you return, not the type you built. Iterator<Integer> iterator() returning a private class Cursor leaves you free to change or delete Cursor later; returning Cursor gives that freedom away.
  • Prefer a lambda for a one-method interface and a static nested class the moment you need state. Lambdas capture only what they use, carry no this$0, and add no class file with a compiler-chosen name.
  • When a callback must outlive the object that created it, pass values rather than the object. A static watcher built as new Watcher(site, limit) is testable in isolation and safe to cache; an anonymous inner one is neither.
  • Make static nested value types final, with final fields and no setters, the way Summary is. A value that cannot change and cannot reach back into its producer is safe to store anywhere, for as long as anyone likes.
  • Never let a nested class print, log or perform I/O on behalf of its owner. Have it return or throw and let the caller decide. ReadingLog's watcher writing to System.out is precisely why that class cannot be unit-tested.

Practice Exercises

  1. The Static Promotion: Take ReadingLog's anonymous watcher and rewrite it as a public static final class PeakWatcher implements Runnable that is constructed with the site name, the limit, and a defensive copy of the accepted readings, and that returns the over-limit count instead of printing it. Give ReadingLog a removeWatcher(Runnable) method as well. Then explain, in two sentences, exactly which objects the static list still retains after your change and which it no longer does.
  2. The Shadow Hunt: Write an Outer class with a private String label = "outer" and an inner class whose constructor takes a String label parameter. Inside the constructor, print all three of label, this.label and Outer.this.label, then assign the parameter to this.label and print all three again. Predict the six lines of output before you run it, then run it and reconcile any line you got wrong.
  3. The Two Probes: Reproduce the Timing demo from this lesson, then add a third probe created by a local class inside an instance method that copies stage into its own final field at construction time. Mutate stage and read all three probes. Explain why the local class can produce either behaviour depending on one line you write, while the two anonymous versions cannot.