Sub topic 13
How Nested Classes Compile: Outer$Inner.class
This chapter assumes you can write and run Java programs from the command line and know the four kinds of nested class: static nested, inner, local, and anonymous. It also assumes you have met effectively final capture. It uses javac, javap, and a little reflection, so you need JDK 11 or later. Where older compilers behaved differently, the text says so.
The JVM has no nested classes
Nesting is a feature of the Java language, not of the JVM. The JVM loads flat classes, each from its own .class file. The compiler therefore turns every nested class into an ordinary top-level class with a mangled name, then adds metadata so that reflection and access checks can recover the nesting.
The rule is simple: one source-level class produces one .class file, no matter how deeply it is nested or whether it has a name. That includes anonymous classes and local classes. It does not include lambdas, covered below.
The naming rules
The compiler builds each binary name from the name of the immediately enclosing class, a $ separator, and a suffix.
| Kind | Binary name pattern | Example |
|---|---|---|
| Top-level | `Outer` | `Outer.class` |
| Static nested or inner member | `Outer$Name` | `Outer$Inner.class` |
| Member nested two levels deep | `Outer$Mid$Name` | `Outer$Mid$Deep.class` |
| Local class | `Outer$<n>Name` | `Outer$1Greeter.class` |
| Anonymous class | `Outer$<n>` | `Outer$1.class` |
Two details matter in practice:
- Static nested and inner member classes get the same kind of name. Nothing in the file name tells you whether the class is static. That information lives inside the class file.
- The number
nis chosen by the compiler. It starts at 1 and takes the first value that is unused for that enclosing class. An anonymous class declared insideOuter.Inneris namedOuter$Inner$1, notOuter$2. Two local classes namedGreeterin different methods of the same class becomeOuter$1GreeterandOuter$2Greeter.
Observing the names
This program declares one class of each kind and prints the names the runtime reports. Save it as Outer.java.
public class Outer {
private int secret = 42;
static class Nested { }
class Inner {
int peek() { return secret; }
}
Object makeLocal() {
class Local { }
return new Local();
}
Object makeAnon() {
return new Object() { };
}
Runnable makeLambda() {
return () -> System.out.println(secret);
}
public static void main(String[] args) {
Outer o = new Outer();
Class<?>[] classes = {
Outer.class, Nested.class, Inner.class,
o.makeLocal().getClass(), o.makeAnon().getClass()
};
for (Class<?> c : classes) {
System.out.println(c.getName() + " | '" + c.getSimpleName()
+ "' | " + c.getCanonicalName());
}
System.out.println(Inner.class.getNestHost().getName());
System.out.println(Outer.class.getNestMembers().length);
}
}Compile and run it:
javac Outer.java
java OuterThe output is:
Outer | 'Outer' | Outer
Outer$Nested | 'Nested' | Outer.Nested
Outer$Inner | 'Inner' | Outer.Inner
Outer$1Local | 'Local' | null
Outer$1 | '' | null
Outer
5The three name methods return different things:
getName()returns the binary name with$. This is the nameClass.forNameexpects, soClass.forName("Outer$Inner")works andClass.forName("Outer.Inner")throwsClassNotFoundException.getSimpleName()returns the name as written in source. For an anonymous class it is the empty string.getCanonicalName()returns the name you would write in source. It isnullfor local and anonymous classes because no source expression can name them.
The compile also produces Outer.class, Outer$Nested.class, Outer$Inner.class, Outer$1Local.class, and Outer$1.class. The last two lines of output show the nest metadata, explained below.
What is inside an inner class file
Because the JVM has no concept of an enclosing instance, the compiler turns the hidden link into ordinary members. Inspect the inner class with javap. The -p flag includes private and synthetic members. Quote the name so the shell does not treat $ as a variable:
javap -p 'Outer$Inner'The output looks roughly like this:
class Outer$Inner {
final Outer this$0;
Outer$Inner(Outer);
int peek();
}The compiler made three changes:
- It added a synthetic field
this$0that holds the enclosing instance.Outer.thisin source becomes a read of this field. - It added a first constructor parameter of type
Outer. Writingouter.new Inner()compiles tonew Outer$Inner(outer). The compiler inserts a null check onouter, which is why((Outer) null).new Inner()throwsNullPointerException. - It kept the field
secretinOuter. The inner class reads it throughthis$0.
A static nested class gets none of this. javap -p 'Outer$Nested' shows only a default constructor. This is the compiled form of the rule that a static nested class has no enclosing instance.
Captured variables
Local and anonymous classes that use a local variable get one synthetic field for each captured variable, conventionally named val$name. The constructor receives the current value. Take Greeters.makeGreeter(String name) from the local class chapter. Its Greeters$1Greeter class has a field final String val$name and a constructor that takes the string. This is the reason captured variables must be effectively final. The class holds a copy, so a later change to the original variable could not be seen by the class and would silently diverge.
Optional `this$0` in newer compilers
Older javac versions always generated this$0 for an inner class, even if the class never used the enclosing instance. Starting with JDK 18, javac omits the field when nothing uses it, which reduces accidental memory retention. It still keeps the constructor parameter, so the construction syntax does not change. Do not rely on this optimization. Code compiled with an older JDK, or an inner class that is serializable, still carries the field.
Private access: synthetic accessors versus nests
Source code allows an outer class and its nested classes to read each other's private members. The JVM, however, treats private as "accessible only from the same class". Outer$Inner and Outer are different classes to the JVM, so something has to bridge the gap.
- Before Java 11,
javacgenerated hidden bridge methods such asstatic int access$000(Outer)in the class that owned the private member. Calls from the nested class went through them. A private constructor needed a synthetic second constructor with an extra parameter of a synthetic type, which is why you could find emptyPizza$1.classfiles next to a builder. These bridges showed up in stack traces and added bytecode. - Since Java 11, class files record nest membership (JEP 181). The outermost class is the nest host and lists its members in a
NestMembersattribute. Each member names its host inNestHost. The JVM lets nestmates access each other's private members directly, so no accessors are generated.
The two calls at the end of the program use this metadata. getNestHost() returned Outer. getNestMembers() returned 5 classes: the host plus Nested, Inner, Local, and the anonymous class. You can also call isNestmateOf to test whether two classes share a nest.
Where the nesting information lives
The compiler also writes an InnerClasses attribute into the class file. It records the original simple name, the enclosing class, and the modifiers, including static and private, which the JVM's own class access flags cannot express. For example, a private nested class is compiled as package-private at the JVM level, and InnerClasses remembers that it was private. Reflection methods such as getModifiers(), getSimpleName(), getEnclosingClass(), and isAnonymousClass() read this attribute. Run javap -v 'Outer$Inner' to see it.
Lambdas are different
A lambda does not produce a Outer$1.class file. The compiler turns the lambda body into a private synthetic method in the enclosing class, named like lambda$makeLambda$0. At run time an invokedynamic instruction creates an object implementing the functional interface. Compare the file lists after compiling Outer.java: the anonymous class has a file, and the lambda in makeLambda has none.
This is a practical reason to prefer lambdas when both work. They add no class files, so jars stay smaller, and each lambda's class is generated on first use instead of loaded from the jar at startup.
Practical consequences
- Anonymous class names are unstable. The numbers follow declaration order, so inserting a new anonymous class earlier in a file renumbers the later ones. Log output, serialized data, and any configuration that mentions
Outer$2can break after an unrelated edit. This is one reason serializing anonymous and local classes is discouraged. - Packaging must include every
$file. If you copy individual class files by hand or filter a build output directory onOuter.class, the nested classes go missing and you getNoClassDefFoundError: Outer$Innerat run time. - Shell quoting. In a shell, write
'Outer$Inner'orOuter\$Inner. Unquoted, the shell expands$Inneras a variable and you get a "class not found" error that looks unrelated. - Stack traces show binary names. A frame such as
at Outer$1.run(Outer.java:12)points to the first anonymous class inOuter. Name important classes, or use a lambda with a clear enclosing method, so traces stay readable. - Class count affects startup. Each nested class is a separate file to find, read, and verify. In very large code bases, thousands of tiny anonymous classes measurably slow loading.
Summary
Every nested class compiles to its own Outer$... file. Inner classes gain a synthetic this$0 field and a constructor parameter. Captured locals become val$ fields. Since Java 11 nest metadata replaces synthetic accessor methods, and lambdas avoid class files altogether.
Exercise
You compile a file Report.java that contains a top-level class Report. Inside it are a static nested class Row, an inner class Cell, one anonymous class in method a(), and a lambda in method b(). Another anonymous class appears in a method of Report.Cell. List the class files you expect, and name the one that a lambda would not add.
Show answer
Report.class, Report$Row.class, Report$Cell.class, Report$1.class (the anonymous class in a()), and Report$Cell$1.class (the anonymous class inside Cell, named after its immediately enclosing class). The lambda adds no file. It becomes a private synthetic method such as lambda$b$0 in Report.class.
Exercise
Why does ((Outer) null).new Inner() fail, and what does this tell you about the compiled constructor of Outer$Inner?
Show answer
The compiler passes the outer instance as a hidden first constructor argument, so outer.new Inner() becomes new Outer$Inner(outer). It checks that argument for null and throws NullPointerException. This shows that the constructor of an inner class takes the enclosing instance as an extra parameter, which it stores in the synthetic field this$0.
Exercise
A teammate says they can find a class by calling Class.forName("Outer.Inner"). What happens, and what should they write instead?
Show answer
It throws ClassNotFoundException, because Class.forName expects the binary name, not the canonical source name. They should write Class.forName("Outer$Inner"). For a class in a package, the package prefix is also needed, for example com.example.Outer$Inner.