Sub topic 11
Static nested classes
A static nested class is a class declared inside another class with the static modifier. This chapter assumes you can write classes with fields, constructors and methods, and that you know access modifiers and the difference between static and instance members from the earlier chapters. You should also know that a static method has no this.
What a static nested class is
A nested class is any class declared inside another class. Java has two kinds of member nested class:
- A static nested class is declared with
static. It belongs to the outer class itself, the way a static field does. - An inner class is declared without
static. Each instance is tied to one instance of the outer class.
The outer class works mostly as a namespace and a grouping tool for a static nested class. The nested class does not need an outer object to exist.
public class Shop {
class Item {} // inner class: needs a Shop object
static class Tag {} // static nested class: needs nothing
public static void main(String[] args) {
Tag t = new Tag();
// Item i = new Item(); // compile error: non-static variable this
// // cannot be referenced from a static context
Item i = new Shop().new Item();
System.out.println(t != null && i != null);
}
}main is static, so there is no this of type Shop. The inner class Item needs one, so new Item() fails. Tag has no such requirement, so new Tag() works. Writing new Shop().new Item() supplies the missing outer object explicitly.
Naming and creating instances
From outside the outer class, you refer to a static nested class by its qualified name, Outer.Nested. You create it with new Outer.Nested(). No outer instance is involved.
Inside the outer class, the simple name Nested is enough. You can also import the nested class like any other type, for example import java.util.Map.Entry;. The compiler produces a separate class file named Outer$Nested.class. At runtime the nested class is a normal class with its own Class object, its own static state and its own initialization.
What a static nested class can access
The access rules follow from the fact that no outer object exists:
- It can use the outer class's static members directly, including private ones.
- It cannot use the outer class's instance members by simple name. It needs an explicit reference to an outer object.
- The outer class can use the nested class's private members, because both are part of the same top-level class.
public class Outer {
private static int staticCounter = 0;
private int instanceValue = 42;
static class Nested {
private int secret = 7;
void show(Outer outer) {
staticCounter++;
System.out.println(staticCounter);
System.out.println(outer.instanceValue);
// System.out.println(instanceValue); // compile error:
// non-static variable instanceValue cannot be referenced
// from a static context
}
}
public static void main(String[] args) {
Outer outer = new Outer();
Nested n = new Nested();
n.show(outer);
System.out.println(n.secret); // allowed: same top-level class
}
}This prints 1, 42 and 7. The error comment has the same cause as in a static method: the nested class has no this for Outer. Passing an Outer as a parameter gives it a reference, and then even private instance fields are accessible.
Static nested versus inner
| Aspect | Static nested class | Inner class |
|---|---|---|
| Needs outer instance to create | No | Yes |
| Holds hidden reference to outer object | No | Yes |
| Can use outer instance members by name | No | Yes |
| Can use outer static members | Yes | Yes |
| Creation from outside | `new Outer.Nested()` | `outer.new Inner()` |
| Memory cost per instance | Only its own fields | Its own fields plus the outer reference |
The hidden reference is the practical difference. The compiler adds a field to each inner instance that points to the outer object. This keeps the outer object reachable for as long as the inner object lives. If you store inner instances in a long-lived collection or hand them to another thread, the outer objects stay in memory too, which is a classic memory leak. A static nested class cannot cause this, because it holds no such reference.
A good default is to start with static and remove it only when the compiler tells you the class really needs the outer instance.
Common uses
A helper type that belongs to one class
Data structures often hide their nodes. The node never needs the structure object, so it is static.
public class IntStack {
private static class Node {
final int value;
final Node next;
Node(int value, Node next) {
this.value = value;
this.next = next;
}
}
private Node top;
private int size;
public void push(int value) {
top = new Node(value, top);
size++;
}
public int pop() {
if (top == null) {
throw new IllegalStateException("stack is empty");
}
int value = top.value;
top = top.next;
size--;
return value;
}
public int size() {
return size;
}
public static void main(String[] args) {
IntStack stack = new IntStack();
stack.push(1);
stack.push(2);
System.out.println(stack.pop());
System.out.println(stack.size());
}
}The output is 2 and then 1. Because Node is private, callers cannot see or depend on it. If Node were an inner class, every node would carry an extra reference to its stack, which wastes memory for no benefit.
The standard library does the same thing. java.util.Map.Entry is a nested interface, and HashMap uses a static nested Node class for its buckets.
The builder pattern
A builder is a nested class that collects values step by step and then creates the outer object. It pairs well with a static factory method from the earlier chapter on factories.
import java.util.ArrayList;
import java.util.List;
public final class Pizza {
private final String size;
private final List<String> toppings;
private Pizza(Builder builder) {
this.size = builder.size;
this.toppings = List.copyOf(builder.toppings);
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private String size = "medium";
private final List<String> toppings = new ArrayList<>();
private Builder() {
}
public Builder size(String size) {
this.size = size;
return this;
}
public Builder topping(String topping) {
toppings.add(topping);
return this;
}
public Pizza build() {
return new Pizza(this);
}
}
@Override
public String toString() {
return size + " pizza with " + toppings;
}
public static void main(String[] args) {
Pizza pizza = Pizza.builder()
.size("large")
.topping("olives")
.topping("basil")
.build();
System.out.println(pizza);
}
}This prints large pizza with [olives, basil]. The builder has to be static, since you need a builder before any Pizza exists. The Pizza constructor is private, but Builder can call it, and Pizza can read the builder's private fields.
The lazy holder idiom
A static nested class is not initialized until it is first used. This lets you delay creating an expensive object without writing any locking code.
public class Registry {
private Registry() {
System.out.println("Registry created");
}
private static class Holder {
static final Registry INSTANCE = new Registry();
}
public static Registry getInstance() {
return Holder.INSTANCE;
}
public static void main(String[] args) {
System.out.println("start");
Registry a = getInstance();
Registry b = getInstance();
System.out.println(a == b);
}
}The output is start, Registry created, true. Loading Registry does not load Holder. The first call to getInstance() touches Holder.INSTANCE, which triggers Holder's static initialization once. The JVM guarantees that class initialization is thread-safe, so two threads calling getInstance() at the same time still get one instance. This builds on the initialization rules from the static blocks chapter, and the next-but-one chapter on thread safety explains why the guarantee holds.
Details and edge cases
Static members inside nested classes
A static nested class can declare its own static fields and methods without restriction. Inner classes could not declare static members, other than compile-time constants, before Java 16. From Java 16 onward they can. Code that must compile on older versions should keep static members in a static nested class or the outer class.
Implicitly static nested types
Some nested types are static even without the keyword:
- A nested
interface,enumorrecordis always implicitly static. - A class declared inside an interface is implicitly
public static.
Writing static on them is allowed but redundant. These types can never capture an outer instance.
Access modifiers on the nested class
Unlike a top-level class, a nested class can be private, protected or package-private as well as public. Use private for implementation details such as Node, and public for types callers must name, such as Pizza.Builder.
Shadowing and naming
A nested class can declare a field with the same name as an outer static field. The nested one shadows the outer one inside the nested body. You reach the outer one with Outer.name. Avoid the clash in the first place, since it makes code hard to read.
Common errors
- "non-static variable this cannot be referenced from a static context". You tried to create an inner class from a static method. Either make the class
staticor create an outer object first. - "non-static variable x cannot be referenced from a static context". A static nested class used an outer instance field by simple name. Pass an outer reference in, or move the field's use elsewhere.
- Making a class static to silence the compiler. If the class really does need outer state, passing the outer object around by hand is usually worse than an inner class.
Exercises
Exercise
A class Cache has a private nested class Entry that stores a key and a value. Entry never reads any field of Cache. Should Entry be static or inner, and what goes wrong if it is inner and a million entries are stored?
Show answer
It should be static. An inner Entry holds a hidden reference to its Cache object, which costs one extra reference per entry (a million of them) and keeps the cache object reachable as long as any entry is. A static nested Entry has neither cost.
Exercise
Given public class Box { private int weight = 5; static class Label { int read() { return weight; } } }, why does this not compile, and give two ways to fix it.
Show answer
Label is a static nested class, so it has no Box instance, and weight is an instance field. One fix is to pass a box in: int read(Box box) { return box.weight; }. The other is to make Label an inner class by removing static, so each Label belongs to a Box and can read weight directly.
Exercise
In the Registry holder example, when does Registry created print, and why does calling getInstance() twice not print it twice?
Show answer
It prints on the first call to getInstance(), because that call first touches Holder.INSTANCE and triggers the one-time initialization of Holder, which runs new Registry(). Static initialization of a class runs only once, so later calls just read the already-created INSTANCE.