Scrivio Interview library
ConceptPrincipal7 min read · updated 12 November 2026

Inner classes were added in Java 1.1 mainly for event listeners, and lambdas in Java 8 replaced most anonymous classes. Explain how each change altered typical Java code, and what lasting problems inner classes still cause in older codebases.

Inner classes, added in Java 1.1, gave Java closures over the enclosing object, which made the new AWT event listeners practical, and anonymous classes became the everyday way to pass behaviour for almost two decades. Lambdas in Java 8 replaced most anonymous classes with expressions compiled through invokedynamic that capture only what they use. Old codebases still suffer from the inner class model: hidden outer references cause memory leaks and serialization problems, and private access needed synthetic accessors until nestmates in JDK 11. Today's standard is static nested classes by default, lambdas for functional interfaces, and inner classes only when outer state is really needed.

Why this question is asked

Senior engineers maintain code from every era of Java, and the way a codebase passes behaviour around tells us when it was written and which problems it is likely to have. Interviewers ask this history question to see whether we understand why the language changed, what the compiler and JVM do differently in each case, and how that knowledge turns into standards for a team. In this answer, we will see what problem inner classes solved in 1.1, what anonymous classes cost, what lambdas changed in Java 8, and which problems from the inner class era still show up in old code, before setting out the standard we would use today.

1Java 1.1: Inner Classes for the New Event Model

Java 1.0 handled GUI events through inheritance: a component overrode a method such as action() and checked which button had fired. Java 1.1 introduced the delegation event model, where any object implementing a listener interface such as ActionListener can register with a component. That needs a convenient way to write many small objects that react to events and work on the state of the window that owns them.

Inner classes were the answer. An inner class, and especially an anonymous one, can be written right where it is registered, and it can read and change the enclosing window's fields as if they were its own. In other words, it is a closure over the enclosing instance. The JVM was not changed for this: javac compiled each inner class to a separate class file and added a hidden this$0 field holding the outer object.

Java
// Java 1.1 to Java 7 style
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
document.save(); // reads the window's field through this$0
}
});
// compiles to EditorWindow$1.class with a field EditorWindow this$0

2The Cost of Anonymous Classes

For the next seventeen years, anonymous classes were how Java passed behaviour: listeners, Runnables, Comparators, callbacks, and later the template-method callbacks of frameworks like Spring's JdbcTemplate. They worked, but they had three costs.

They were verbose: five lines of ceremony for one line of logic. Every anonymous class was a separate class file, EditorWindow$1, $2 and so on, which the JVM had to load, verify and keep in metaspace, so a large application could have thousands of them. And every one created in an instance method carried the outer reference, whether it needed it or not.

3Java 8: Lambdas and invokedynamic

Lambdas replaced most anonymous classes for interfaces with a single abstract method. The syntax is the visible change, but the implementation matters more. javac compiles the lambda body into a private method of the enclosing class and emits an invokedynamic instruction at the place where the lambda is created. The first time that instruction runs, the JVM calls a bootstrap method, LambdaMetafactory, which creates a small hidden class at runtime implementing the interface and links the call site to it.

Java
button.addActionListener(e -> document.save());
// no EditorWindow$1.class on disk; the body becomes a private method like lambda$new$0
// captures this only because document is an instance field
Comparator<String> byLength = Comparator.comparingInt(String::length);
// captures nothing: the JVM can reuse one instance for every evaluation
Anonymous class versus lambda
AspectAnonymous classLambda
Class fileone per use, Outer$1.classnone; class generated at runtime
Outer referencealways in instance context (this$0)only if it uses instance members
this inside the bodythe anonymous objectthe enclosing object
Allocationnew object on every evaluationnon-capturing: one shared instance
Can implementany interface or abstract classfunctional interfaces only
Statemay have its own fieldsno fields of its own

Notice two improvements. A lambda captures only what it uses: if it uses no instance member, it holds no reference to this, and a non-capturing lambda can be a single shared instance. And the strategy for creating the implementation is decided by the JVM at runtime, not frozen into class files, so later JDKs could improve it without recompiling anything.

4Problems Inner Classes Still Cause in Old Code

The first lasting problem is memory leaks. An inner or anonymous class registered with something long-lived, such as a static registry, a cache or a scheduled executor, keeps the outer object alive through this$0. In old Swing, Android and server code, this is one of the most common leak patterns found in heap dumps.

The second is serialization. Serializing an inner class instance also tries to serialize its outer instance through the hidden field, so it either fails with NotSerializableException or silently drags a large object graph into the stream. Worse, the names and layout of the synthetic fields are compiler details, so serialized inner classes may not be compatible across compilers, which is why the Java serialization specification strongly discourages serializing them. Old session objects and cached objects in distributed caches still hit this.

The third is bytecode noise from private access. Before JDK 11, inner classes that used private members of the outer class, or the reverse, required javac to generate synthetic access$000 methods. Code compiled for old targets still carries them, and they appear in stack traces and profiles. Nestmates in JDK 11 let the JVM allow such access directly, but only for code recompiled with a target of 11 or later.

5The Standard We Would Set Today

The history gives a clear standard. Nested types are static by default: builders, entries, helper types and records do not get an outer reference unless they need one. Behaviour passed as an argument is a lambda or a method reference whenever the target is a functional interface. Anonymous classes remain for the cases a lambda cannot express: an interface with several methods, an abstract class, or a callback that needs its own fields. Inner classes are used only when the code genuinely works on the outer instance's state, such as an iterator over its own collection, and never for objects that are registered somewhere long-lived or serialized.

In old code, we do not rewrite everything at once. Tools such as IntelliJ inspections and OpenRewrite recipes can convert anonymous classes to lambdas and flag inner classes that could be static, and we apply them module by module, starting with code that shows up in heap dumps.

6Follow-up questions

Why does this mean different things in an anonymous class and in a lambda?

An anonymous class is a real object of its own class, so this inside it is that object, and the outer object is Outer.this. A lambda is not a new scope for this; it is lexically scoped, so this inside a lambda is the enclosing object. That is also why a lambda that uses this captures the enclosing instance.

Are lambdas always cheaper than anonymous classes?

Usually, but not in every respect. The first evaluation of each lambda call site runs the bootstrap and spins a class, which costs some startup time; CDS and the AOT cache reduce that. After linking, capturing lambdas still allocate an object per evaluation, just as anonymous classes do. The real wins are fewer class files, no needless outer references and shared non-capturing instances.

Can lambdas be serialized?

Only if the target type is serializable, for example by casting to an intersection type with Serializable, and then the lambda is serialized through a special form that depends on the enclosing class. It is fragile across code changes, so we avoid serializing lambdas, for the same reasons we avoid serializing inner classes.

7Conclusion

In this answer, we followed behaviour passing through Java's history. Inner classes in 1.1 gave closures over the enclosing instance for the new listener model, at the cost of a class file per use and a hidden outer reference. Lambdas in Java 8, compiled with invokedynamic and capturing only what they use, replaced most anonymous classes. In old code, inner classes still cause memory leaks, serialization problems and synthetic accessors from before nestmates, so today we use static nested classes by default, lambdas for functional interfaces, and inner classes only when outer state is needed.

What to say in the interviewAbout 90 seconds aloud

Open with

Inner classes came in Java 1.1 together with the delegation event model in AWT, where listeners are separate objects. An anonymous inner class let us write the listener right where we registered it and work on the window's fields directly, so it was a closure over the enclosing instance, done by javac with a separate class file and a hidden this$0 field.

Then, if they want more

For about seventeen years anonymous classes were how Java passed behaviour, which meant verbose code, a class file per use and an outer reference whether it was needed or not. Java 8 lambdas changed that.

The body becomes a private method, the creation site is an invokedynamic call that the LambdaMetafactory links to a class generated at runtime, a lambda captures this only when it uses instance members, and non-capturing lambdas can be shared. In old code, the inner class model still causes three problems. Inner classes registered with long-lived registries leak their outer objects.

Serializing them drags in or fails on the outer instance, and their synthetic fields are compiler-specific. And before JDK 11, private access between nested classes needed access$ accessors, which nestmates removed only for recompiled code.

So my standard is static nested classes by default, lambdas or method references for functional interfaces, anonymous classes only where a lambda cannot work, and inner classes only when the code truly needs the outer instance's state.

About this answer

Last updated
12 November 2026
Versions it names
Java 11, Java 8, Java 7
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Inner classes were added in Java 1.1 mainly for event listeners, and lambdas in Java 8...": https://scrivio-interview-library.netlify.app/java/classes-and-objects/ac9f813046/