Sub topic 3
Inner classes and their link to an outer object
This chapter covers the non-static member class, usually just called an inner class. It assumes you can write and compile basic Java classes and know access modifiers, instance versus static members, and interfaces with method overriding. You should also be able to read simple generic code such as Iterator<Integer>.
What makes a class "inner"
A member class is declared directly in the body of another class, outside any method. If you leave off static, it is an inner class. The one-word difference changes how the class works:
- A static nested class is an ordinary class that lives in the outer class's namespace. It needs no outer object.
- An inner class is tied to one specific instance of the outer class. Every inner object is created with an outer object attached, and it cannot exist without one.
The attached outer object is called the enclosing instance. The inner object uses it to read and write the outer object's fields and to call its methods. This link is the main reason to choose an inner class.
public class Counter {
private int count;
public class Incrementer {
private final int step;
public Incrementer(int step) { this.step = step; }
public void run() { count += step; }
public Counter owner() { return Counter.this; }
}
public int get() { return count; }
public static void main(String[] args) {
Counter c = new Counter();
Counter.Incrementer inc = c.new Incrementer(2);
inc.run();
inc.run();
System.out.println(c.get()); // 4
System.out.println(inc.owner() == c); // true
}
}In run(), the name count is not declared in Incrementer. Java finds it in the enclosing class and treats it as Counter.this.count. The method changes the field of the Counter that inc belongs to, not a copy and not a different Counter.
Two syntax forms appear here, and the next chapter covers them in full:
c.new Incrementer(2)creates an inner object attached to the specific outer objectc.Counter.thisnames the enclosing instance from inside the inner class.
Each inner object belongs to one outer object
The link is per object, not per class. Several inner objects can share one outer object, and inner objects of different outer objects stay separate.
public class TwoCounters {
private int count;
class Step {
private final int amount;
Step(int amount) { this.amount = amount; }
void apply() { count += amount; }
}
Step stepOf(int amount) {
return new Step(amount); // implicitly this.new Step(amount)
}
public static void main(String[] args) {
TwoCounters a = new TwoCounters();
TwoCounters b = new TwoCounters();
Step s1 = a.new Step(1);
Step s2 = a.new Step(10);
Step s3 = b.stepOf(100);
s1.apply();
s2.apply();
s3.apply();
System.out.println(a.count); // 11
System.out.println(b.count); // 100
}
}s1 and s2 both update a. s3 updates b. Inside an instance method such as stepOf, a plain new Step(amount) works because the current object, this, becomes the enclosing instance automatically.
The most common error: creating an inner object without an outer one
Suppose you write new Step(5) inside main, which is a static method. There is no this in a static method, so no enclosing instance is available. The compiler rejects the code with an error such as non-static variable this cannot be referenced from a static context.
You have two valid fixes:
- Supply the outer object explicitly:
someOuter.new Step(5). - If the class never uses the outer object, declare it
static. It then becomes a static nested class and the problem disappears.
Access to the outer object's private members
An inner class can read and write every member of its enclosing class, including private fields and private methods, and the enclosing class can do the same to the inner class. They share a top-level class, so Java treats them as one unit for access purposes.
Access also runs through the chain of enclosing classes. If A contains B and B contains C, then C can use the private members of both B and A. Each use goes through the matching enclosing instance.
This makes inner classes a good fit for helper objects that expose a controlled view of private state, as in an iterator:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Ring implements Iterable<Integer> {
private final int[] data;
public Ring(int... data) { this.data = data; }
@Override
public Iterator<Integer> iterator() {
return new RingIterator();
}
private class RingIterator implements Iterator<Integer> {
private int index;
@Override
public boolean hasNext() { return index < data.length; }
@Override
public Integer next() {
if (!hasNext()) throw new NoSuchElementException();
return data[index++];
}
}
public static void main(String[] args) {
for (int n : new Ring(10, 20, 30)) {
System.out.println(n);
}
}
}Three design points are worth noting:
RingIteratorreadsdatadirectly. TheRingclass needs no getter or copy method for it.- The class is
private, so callers only ever see it as anIterator<Integer>. They cannot depend on its name or its extra members. - Each call to
iterator()creates a newRingIteratorwith its ownindex, so two loops over the sameRingdo not interfere with each other. Both iterators share the singledataarray through their enclosing instance.
Which access modifiers apply
Because an inner class is a member of its outer class, it accepts the same four access levels as a field or method:
| Modifier | Who can name the inner class |
|---|---|
| `public` | Any code that can see the outer class |
| `protected` | The same package and subclasses of the outer class |
| package-private (none) | The same package |
| `private` | Only code inside the same top-level class |
A top-level class can only be public or package-private. Inner classes get the full range, which lets you hide an implementation class completely.
You can also mark an inner class final or abstract, and it can extend a class or implement interfaces like any other class. An inner class can even extend its own outer class, though that is rarely a good idea.
What an inner class can declare
Inner classes have limits on static members. Before Java 16, an inner class could not declare static methods or static fields. The only exception was a constant variable, meaning a static final primitive or String with a compile-time constant value. From Java 16 on, inner classes can declare static members freely. If your project must build on older Java versions, check which version you target. A later chapter covers these declaration rules in full.
Inner classes and memory
The link to the outer object is a real reference stored in every inner object. The compiler adds a hidden field, usually called this$0, and fills it in the constructor. This has a practical consequence: an inner object keeps its outer object reachable. The garbage collector cannot free the outer object while any inner object still refers to it.
This is usually harmless, but it becomes a leak when the inner object lives much longer than the outer one:
- An inner object is stored in a long-lived structure, such as a static field, a cache, or a registered listener list.
- The outer object is large, for example it holds a big array or a whole document, and you expected it to be discarded.
Ring.RingIterator needs the outer object to reach data, so the link is justified. A cache entry class that only stores a key and a value does not need it, and it should be static. A later chapter covers detecting and removing these hidden references.
Compiled form
The compiler turns every inner class into its own class file. Counter.Incrementer compiles to Counter$Incrementer.class. Its constructor receives the enclosing instance as an extra first parameter, which is how c.new Incrementer(2) passes c along. You do not write that parameter in source code. You can see it by running javap -p 'Counter$Incrementer'.
Choosing between inner and static nested
| Question | If yes |
|---|---|
| Does each instance need to read or write one specific outer object's state? | Inner class |
| Can the class work from its constructor arguments alone? | Static nested class |
| Will instances be stored somewhere that outlives the outer object? | Prefer static nested |
| Do you want to hide the class from all callers? | Either one, declared `private` |
Start with static, and remove it only when the class really needs the enclosing instance.
Exercise
A class Library has a private List<String> books field and an inner class Cursor that walks over books. The code Library.Cursor c = new Library.Cursor(); inside main fails to compile. Give two ways to make it work, and say which one you would pick if Cursor only needs a copy of the list taken at creation time.
Show answer
First, create an outer object and attach the cursor to it: Library lib = new Library(); Library.Cursor c = lib.new Cursor();. Second, make Cursor a static nested class, so new Library.Cursor() is valid without an outer object. A static class cannot read books through an enclosing instance, so it would take the list as a constructor argument. If Cursor only needs a copy of the list taken at creation time, pick the static nested class. It holds no hidden reference to the Library, so the library can be garbage collected while the cursor is still in use.
Exercise
In TwoCounters, s1 and s2 were created with a.new Step(...), and s3 with b.stepOf(100). After all three apply() calls, which counter changes when you call s3.apply() again, and why?
Show answer
Counter b changes. stepOf is an instance method called on b, so new Step(amount) inside it uses b as the enclosing instance. s3 keeps that reference for its whole life, so every apply() adds to b.count, never to a.count.