Sub topic 2
Static nested classes
This chapter assumes you can write and compile basic Java classes. It also assumes you know access modifiers, the difference between instance and static members, and how interfaces and abstract classes work. Static nested classes are the simplest of the four kinds of nested class. The rest of the tutorial builds on them.
What a static nested class is
A static nested class is a class declared inside another class with the static modifier. It is a member of the enclosing class, in the same way a static method or static field is.
public class Outer {
static class Nested {
}
}The static keyword means the nested class is not tied to any instance of Outer. You can create a Nested object without ever creating an Outer object. Compared with a top-level class, a static nested class differs in two ways:
- Its name is qualified by the enclosing class (
Outer.Nested), which groups related types together. - It shares private access with the enclosing class, as described below.
Apart from those two points, it behaves like an ordinary top-level class. It has its own constructors, fields, and methods, and it can extend a class and implement interfaces.
Why nest a class at all
Nest a class when it exists only to serve the enclosing class. There are three common reasons:
- Grouping.
Map.Entryis meaningless withoutMap. Nesting documents that relationship in the name itself. - Encapsulation. A
private staticnested class is invisible outside the file's top-level class. Its API can change without breaking callers. - Less clutter. Helper types such as builders, nodes, and key objects do not need their own files or a place in the package namespace.
Worked example: a builder
The builder pattern is the standard use of a static nested class. The Pizza constructor is private, so only Builder can create a Pizza.
public class Pizza {
private final String size;
private final boolean cheese;
private Pizza(Builder b) {
this.size = b.size;
this.cheese = b.cheese;
}
public static class Builder {
private String size = "medium";
private boolean cheese;
public Builder size(String size) { this.size = size; return this; }
public Builder cheese(boolean cheese) { this.cheese = cheese; return this; }
public Pizza build() { return new Pizza(this); }
}
@Override
public String toString() {
return size + (cheese ? " with cheese" : "");
}
public static void main(String[] args) {
Pizza p = new Pizza.Builder().size("large").cheese(true).build();
System.out.println(p); // large with cheese
}
}Three details in this code matter:
new Pizza.Builder()needs noPizzainstance. The builder must exist before thePizzadoes. IfBuilderwere an inner class, you could not construct it first.Buildercalls the privatePizzaconstructor. Both classes live in the same top-level class, so private access is allowed.Pizzareadsb.sizeandb.cheesedirectly. These fields are private inBuilder, and the enclosing class can still read them. There is no need for getters.
How to create and refer to one
Inside the enclosing class, you can use the simple name: new Builder(). From other code, use the qualified name: new Pizza.Builder(). You can also import the nested class and use its simple name:
import java.util.Map;
import java.util.Map.Entry;
public class ImportDemo {
public static void main(String[] args) {
Map<String, Integer> ages = Map.of("Ada", 36);
for (Entry<String, Integer> e : ages.entrySet()) {
System.out.println(e.getKey() + " " + e.getValue()); // Ada 36
}
}
}Entry is a nested interface. Nested interfaces, enums, and records are implicitly static, so you never need to write static on them.
The one hard rule: no implicit outer instance
A static nested class has no hidden reference to an Outer object. Inside Nested:
- You can use
Outer's static members directly, including private ones. - You cannot use
Outer's instance fields or instance methods by simple name. The compiler reports an error such as "non-static variable cannot be referenced from a static context". - To use instance members, you need an explicit
Outerreference, passed as a parameter or stored in a field.
The next example shows all three accesses.
public class Registry {
private static int created;
private final String name;
public Registry(String name) {
this.name = name;
created++;
}
public static class Entry {
private final String key;
public Entry(String key) { this.key = key; }
String describe(Registry r) {
// created: outer static field, used by simple name.
// r.name: outer instance field, needs an explicit reference.
return key + " in " + r.name + " (total " + created + ")";
}
}
public static void main(String[] args) {
Registry r = new Registry("main");
Registry.Entry e = new Registry.Entry("k1");
System.out.println(e.describe(r)); // k1 in main (total 1)
System.out.println(e.key); // k1 (outer reads nested private)
}
}The last line shows that private access works in both directions. Registry.main reads Entry.key, which is private. Chapter 10 covers this in more detail.
What a static nested class may declare
A static nested class has no restrictions on its members. It can declare:
- Static and instance fields, methods, and initializers.
- Its own static nested classes, and inner classes.
- Any access modifier:
public,protected, package-private, orprivate. The outer class can use all four, which is unlike a top-level class, where onlypublicand package-private are allowed. abstractorfinal, andextendsandimplementsclauses.
The table compares it with other types of class.
| Feature | Top-level class | Static nested class | Inner class |
|---|---|---|---|
| Needs an outer instance to create | No | No | Yes |
| Can use outer instance members by simple name | Not applicable | No | Yes |
| Can be `private` | No | Yes | Yes |
| Can access outer private members | No | Yes | Yes |
| Has its own `.class` file | Yes | Yes (`Outer$Nested`) | Yes (`Outer$Inner`) |
Compiled form
The compiler turns every nested class into a separate class file. Pizza.Builder becomes Pizza$Builder.class. This matters when you inspect build output, write reflection code, or read stack traces.
public class NameDemo {
static class Nested { }
public static void main(String[] args) {
System.out.println(Nested.class.getName()); // NameDemo$Nested
System.out.println(Nested.class.getSimpleName()); // Nested
}
}getName() returns the binary name with $. getSimpleName() returns only the nested name. Use Class.forName("NameDemo$Nested") when loading by name, not the dotted form.
Common errors and gotchas
- Making a nested class inner by accident. If you omit
staticon a member class that does not need an outer instance, every object carries a hidden reference to its creator. That wastes memory and can keep the outer object alive. Chapter 12 covers the consequences. - Using a non-static class from a static method.
new Builder()insidestatic void mainfails ifBuilderis an inner class, because there is no enclosing instance. MakingBuilderstatic fixes it. - Using the dotted name for reflection.
Class.forName("Pizza.Builder")throwsClassNotFoundException. Use"Pizza$Builder". - Expecting a static nested class to be a singleton.
statichere describes the lack of an outer instance. It does not limit the number of instances of the nested class. - Hiding too much. A
private staticnested class cannot be used as a parameter type in public methods without exposing it. Callers cannot name it, so such an API is hard to use.
Summary
A static nested class is an ordinary class that lives inside another class for grouping and encapsulation. It needs no outer instance, uses the outer class's static members by simple name, and shares private access with the outer class in both directions. It compiles to Outer$Nested.class.
Exercise
In the Registry example, the method Entry.describe takes a Registry parameter. Why can't it simply write name instead of r.name, and how would the declaration of Entry need to change for name to work by itself?
Show answer
Entry is a static nested class, so it has no enclosing Registry instance, and the compiler cannot decide which Registry's name field name refers to. Removing static from Entry would make it an inner class that holds a hidden reference to a Registry, and then name would mean Registry.this.name. Entry would then have to be created with an existing Registry, such as r.new Entry("k1"), and every Entry would keep its Registry alive.
Exercise
What are the output of Pizza.Builder.class.getName() and the file name the compiler produces for it?
Show answer
Both use the binary name Pizza$Builder: getName() prints Pizza$Builder, and the compiler writes Pizza$Builder.class.