Java Inner Classes: Accessing Outer Object State
Understand Java inner classes: why they exist, how an inner object accesses the private fields of its outer object, the hidden this$0 reference, OuterClass.this and outer.new Inner() syntax, static members in inner classes (Java 16), and how the compiler translates them.
kvi5hnuCode Sprout team member10 min readOn this page
An inner class is a class defined inside another class. Why would you want that? There are two reasons:
- Inner classes can be hidden from other classes in the same package.
- Inner class methods can access the data of the scope in which they're defined, including data that would otherwise be private.
Inner classes used to be very important for concisely implementing callbacks, but nowadays lambda expressions do that much better. Still, inner classes are very useful for structuring code: iterators over a collection, nodes of a linked list, builders, and event handlers that need a lot of the outer object's state. This article covers inner classes proper (non-static member classes). The next article covers local, anonymous and static nested classes.
Using an Inner Class to Access Object State
The syntax for inner classes is rather complex, so let's use a simple, somewhat artificial example. We refactor the timer example from the callbacks article and extract a TalkingClock class. Its constructor takes the interval between announcements and a flag to turn beeps on or off:
public class TalkingClock {
private int interval;
private boolean beep;
public TalkingClock(int interval, boolean beep) { . . . }
public void start() { . . . }
public class TimePrinter implements ActionListener { // an inner class
. . .
}
}
The TimePrinter class is now located inside TalkingClock. That doesn't mean every TalkingClock has a TimePrinter field. As you'll see, TimePrinter objects are constructed by methods of TalkingClock.
Here's TimePrinter in more detail. Its actionPerformed method checks the beep flag before beeping:
public class TimePrinter implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("At the tone, the time is "
+ Instant.ofEpochMilli(event.getWhen()));
if (beep) Toolkit.getDefaultToolkit().beep();
}
}
Something surprising is going on. TimePrinter has no field or variable named beep. Instead, beep refers to the field of the TalkingClock object that created this TimePrinter. An inner class method can access both its own fields and those of the outer object creating it.
The Hidden Outer Reference
For this to work, an inner class object always gets an implicit reference to the object that created it.

The reference is invisible in the inner class definition. To illustrate the concept, let's call it outer. Then actionPerformed is equivalent to:
public void actionPerformed(ActionEvent event) {
System.out.println("At the tone, the time is " + Instant.ofEpochMilli(event.getWhen()));
if (outer.beep) Toolkit.getDefaultToolkit().beep();
}
The outer reference is set in the constructor. The compiler modifies all inner class constructors, adding a parameter for the outer reference. TimePrinter defines no constructors, so the compiler synthesizes a no-argument constructor and generates code like this:
public TimePrinter(TalkingClock clock) { // automatically generated code
outer = clock;
}
Again, outer isn't a Java keyword; it just illustrates the mechanism. When start constructs a TimePrinter, the compiler passes the current talking clock's this reference into the constructor:
var listener = new TimePrinter(this); // parameter automatically added
Look at the access control once more. Had TimePrinter been a regular class, it would have needed a public method of TalkingClock to read the beep flag. The inner class is an improvement: there's no need for accessors that are of interest to only one other class.
Here's the complete program, with a simulated timer so it runs anywhere. With a real javax.swing.Timer, start would create new Timer(interval, listener) and call timer.start().
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.time.Instant;
public class Solution {
public static void main(String[] args) {
var clock = new TalkingClock(1000, true);
clock.start(3); // simulated timer: three ticks
// outerObject.new InnerClass(): attach a TimePrinter to another clock
var jabberer = new TalkingClock(500, false);
TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
listener.tick(Instant.parse("2026-11-13T12:00:00Z"));
// static members in inner classes (Java 16+)
System.out.println("printers created: " + TalkingClock.TimePrinter.created());
// what the compiler generated
for (Class<?> cl : new Class<?>[] { TalkingClock.TimePrinter.class, TalkingClock.Quiet.class }) {
System.out.print(cl.getName() + " fields:");
for (Field f : cl.getDeclaredFields())
System.out.print(" " + Modifier.toString(f.getModifiers()) + " "
+ f.getType().getSimpleName() + " " + f.getName()
+ (f.isSynthetic() ? " (synthetic)" : ""));
System.out.println();
}
}
}
/** A clock that prints the time in regular intervals. */
class TalkingClock {
private final int interval;
private final boolean beep;
public TalkingClock(int interval, boolean beep) {
this.interval = interval;
this.beep = beep;
}
/** Starts the clock; here we simulate the timer firing n times. */
public void start(int ticks) {
var listener = new TimePrinter(); // same as this.new TimePrinter()
Instant t = Instant.parse("2026-11-13T09:00:00Z");
for (int i = 0; i < ticks; i++) {
t = t.plusMillis(interval);
listener.tick(t);
}
}
public class TimePrinter { // an inner class
private static int count; // allowed since Java 16
public TimePrinter() { count++; }
public void tick(Instant when) {
System.out.println("At the tone, the time is " + when);
if (beep) System.out.println(" BEEP"); // beep is the outer object's private field
if (TalkingClock.this.interval < 1000) // explicit outer reference
System.out.println(" (fast clock: " + TalkingClock.this.interval + " ms)");
}
public static int created() { return count; }
}
class Quiet { // never touches the outer object
void hush() { System.out.println("..."); }
}
}
At the tone, the time is 2026-11-13T09:00:01Z
BEEP
At the tone, the time is 2026-11-13T09:00:02Z
BEEP
At the tone, the time is 2026-11-13T09:00:03Z
BEEP
At the tone, the time is 2026-11-13T12:00:00Z
(fast clock: 500 ms)
printers created: 2
TalkingClock$TimePrinter fields: private static int count final TalkingClock this$0 (synthetic)
TalkingClock$Quiet fields:
Special Syntax Rules for Inner Classes
OuterClass.this
We've called the outer reference outer. The proper syntax is a bit more complex. The expression
OuterClass.this
denotes the outer class reference. For example, you can write actionPerformed as
public void actionPerformed(ActionEvent event) {
. . .
if (TalkingClock.this.beep) Toolkit.getDefaultToolkit().beep();
}
You need it when a name in the inner class shadows an outer field, or when you want to pass the outer object somewhere, for example list.remove(TalkingClock.this). Plain this inside the inner class means the inner object.
outerObject.new InnerClass()
Conversely, you can write the inner object construction more explicitly, with the syntax
outerObject.new InnerClass(construction arguments)
For example:
ActionListener listener = this.new TimePrinter();
Here the new TimePrinter's outer reference is set to the this of the method creating it. That's the most common case, and as always, this. is redundant. But you can also attach the inner object to another outer object by naming it explicitly. Since TimePrinter is a public inner class, you can construct one for any talking clock:
var jabberer = new TalkingClock(1000, true);
TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
Outside the scope of the outer class, you refer to an inner class as OuterClass.InnerClass. And without an outer object, you can't create an inner object at all: in a static method, new TimePrinter() fails with non-static variable this cannot be referenced from a static context.
Static members in inner classes
As of Java 16, inner classes can have static members. Previously, static methods in inner classes were disallowed, and static fields in an inner class had to be final and initialized with a compile-time constant. Static methods of an inner class can access static fields and methods of the inner class or of enclosing classes, but of course not the outer instance, since they have no this. The demo's TimePrinter.created() counts how many printers exist. (The same Java 16 change allowed records, enums and interfaces to be declared inside inner classes.)
Are Inner Classes Useful? Necessary? Secure?
When inner classes were added in Java 1.1, many programmers considered them a major feature at odds with Java's philosophy of being simpler than C++. The syntax is undeniably complex (it gets more so with anonymous classes), and it isn't obvious how inner classes interact with access control and security.
What the compiler generates
Inner classes are a compiler feature, not a virtual machine feature. They're translated into regular class files with $ separating the outer and inner class names. TimePrinter inside TalkingClock becomes TalkingClock$TimePrinter.class. To see the result, run the ReflectionTest program from the reflection article on TalkingClock$TimePrinter, or use the javap utility:
javap -private TalkingClock\$TimePrinter
(On Unix shells, escape the $, or quote the class name.) For the demo's classes, the output is:
public class TalkingClock$TimePrinter {
private static int count;
final TalkingClock this$0;
public TalkingClock$TimePrinter(TalkingClock);
public void tick(java.time.Instant);
public static int created();
}
The compiler generated an additional field, this$0, for the outer reference. The name is synthesized by the compiler and you can't refer to it in your code; reflection marks it as synthetic. You can also see the added TalkingClock parameter of the constructor.
Since Java 18, the this$0 field is generated only when it's actually needed. The demo's Quiet class never uses its outer object, so it has no fields at all, although its constructor still receives the outer object. That change removes a classic memory leak, where an inner object kept a large outer object alive without using it.
Could you do it by hand?
If the compiler can do this transformation, couldn't you program the same mechanism yourself? Let's try. Make TimePrinter a regular top-level class, and pass it the this reference of the creating object:
class TalkingClock {
. . .
public void start() {
var listener = new TimePrinter(this);
var timer = new Timer(interval, listener);
timer.start();
}
}
class TimePrinter implements ActionListener {
private TalkingClock outer;
. . .
public TimePrinter(TalkingClock clock) {
outer = clock;
}
}
Now actionPerformed needs outer.beep:
if (outer.beep) . . . // ERROR
There's the problem: the inner class could access the private data of the outer class, but the external TimePrinter can't. Inner classes are genuinely more powerful than regular classes because they have more access privileges.
When to Use Inner Classes
| Situation | Choose |
|---|---|
| A short callback or one-method behavior | A lambda or method reference |
| A helper that needs the outer object's state (iterator, view, listener with several methods) | An inner class, often private |
| A helper that doesn't need the outer object (list node, builder, map entry) | A static nested class (next article) |
| A class used by many other classes | A top-level class |
A good rule: if a nested class doesn't need the outer instance, make it static. That avoids the hidden reference, the memory cost and the leak risk.
Common questions
When should a nested class be an inner (non-static) class?
Only when each nested object really needs to work with a specific outer object, like an iterator that walks its list. Otherwise make it static, so it doesn't carry a hidden reference that can keep a large outer object alive.
Can an inner class have static members? Since Java 16, yes: static fields, static methods, and nested records, enums and interfaces. Before Java 16, only compile-time constants were allowed.
How do I create an inner class object from outside the outer class?
Use outer.new Inner(), for example TalkingClock.TimePrinter p = clock.new TimePrinter();, and only if Inner is accessible. Without an outer object, you can't create an inner object at all.
Can inner classes access the outer class's private fields?
Yes. Since Java 11, the JVM supports this directly through nestmates: the outer class and its nested classes may access each other's private members. Older compilers generated hidden access$ methods to achieve the same.
Are inner classes still relevant with lambdas?
Yes, for structure rather than for callbacks. Iterators, nodes, builders and views (Map.entrySet()) are naturally written as nested classes. For short callbacks, lambdas have replaced most anonymous inner classes.
Summary
- An inner class is a non-static class declared inside another class. It can be hidden (
private) and can access all fields of its outer object, including private ones. - Each inner object holds an implicit reference to the outer object that created it, written
OuterClass.thisin code and stored in a syntheticthis$0field (only when needed, since Java 18). - The compiler adds an outer-object parameter to inner class constructors. Use
outer.new Inner(...)to choose the outer object explicitly. Outside, name the classOuter.Inner. - Inner classes may have static members since Java 16.
- Inner classes compile to separate class files such as
TalkingClock$TimePrinter.class. Since Java 11, nestmate access lets them use private members without synthetic accessors.
Practice Questions
Inside an inner class Iter of class MyList, how do you refer to MyList's field size if Iter also has a field named size?
Use MyList.this.size for the outer field. Plain size or this.size refers to Iter's own field.
In a static main method, how do you create a TimePrinter for a clock object c?
TalkingClock.TimePrinter p = c.new TimePrinter(); A plain new TimePrinter() has no outer object in a static context and doesn't compile.
What file does the compiler produce for class Node nested inside class LinkedList, and why does javap show an extra constructor parameter for an inner class?
LinkedList$Node.class. For an inner (non-static) class, the compiler adds a parameter that passes the outer object, which is stored in the synthetic this$0 field when needed.
Why can an inner class read a private field of its outer class, while a top-level class with a reference to the outer object can't?
Private access is granted to the whole top-level class body, including nested classes. The JVM enforces this through nestmate attributes since Java 11. A separate top-level class isn't a nestmate, so the access rules forbid it.
A long-lived listener is an inner class of a huge Document object but never uses it. Why could that leak memory before Java 18, and what's the better design?
The inner object held a hidden reference to the Document, keeping it reachable as long as the listener lived. Declare the class static (or use a lambda that doesn't capture this), so no outer reference exists.
Previous: Java Lambda Variable Scope, Processing Lambdas and Comparator Methods
Related reading
- Java Inheritance Design Hints: Best Practices for Class Hierarchies
- Java Reflection: Analyzing Classes and Inspecting Objects at Runtime
- Java Reflection: The Class Class, Exceptions Primer and Loading Resources
- Java Sealed Classes and Interfaces: Controlling Inheritance
- Java Enum Classes: Enumerated Types with Fields and Methods

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.