Sub topic 11
What nested classes may declare
This chapter covers which members and nested types each kind of nested class may declare, and which modifiers each kind accepts. These rules are among the few that changed between Java versions, so the chapter marks where. It assumes you can already tell static nested, inner, local, and anonymous classes apart.
Two rule sets: members and modifiers
Two questions come up repeatedly:
- Which members may the class body contain? Static fields, static methods, static initializers, constructors, instance initializers, and nested types.
- Which modifiers may the class declaration carry? For example
public,private,static,final,abstract.
The answers differ for each kind of nested class. A nested class is not just a top-level class placed inside another one.
Static nested classes: no restrictions on members
A static nested class behaves like a top-level class that happens to live inside another one. It can declare anything a top-level class can:
- Instance and static fields and methods.
- Constructors.
- Static and instance initializer blocks.
- Further nested types of any kind.
Its declaration may use any access modifier: public, protected, private, or package-private. It may also be final, abstract, or sealed. The only restriction is on what it can reach in the outer class. It has no enclosing instance, so it cannot use the outer class's instance members directly.
Inner classes: static members since Java 16
An inner class is a non-static member class. Its declaration accepts the same access modifiers as a static nested class, plus final and abstract. It cannot be declared static, because that would make it a static nested class.
Before Java 16 an inner class could not declare static members. Since Java 16, it can:
public class Registry {
class Entry {
static int created = 0;
static String describe() {
return "entries: " + created;
}
Entry() {
created++;
}
}
public static void main(String[] args) {
Registry r = new Registry();
r.new Entry();
r.new Entry();
System.out.println(Entry.describe()); // entries: 2
}
}The created counter belongs to the Entry class itself, not to any Registry or Entry instance. Static members of an inner class still cannot refer to the enclosing instance, because no instance is involved when a static method runs.
Two rules hold for every kind of nested class:
- A nested class cannot have the same simple name as any class that encloses it.
class Outer { class Outer {} }does not compile. - Nested types declared inside an inner class are allowed to be static, again since Java 16.
Records, enums, and interfaces are implicitly static
Three kinds of nested type are always static, whether or not you write the keyword:
- A nested record.
- A nested enum.
- A nested interface (including annotation interfaces).
Because they are static, they have no enclosing instance. They can use the outer class's static members, but not its instance members.
public class Shapes {
private static int counter = 0;
private int instanceCount = 0;
record Point(int x, int y) {
// instanceCount is not accessible here: a record is implicitly static
}
enum Kind { CIRCLE, SQUARE }
interface Visitor {
void visit(Point p);
}
public static void main(String[] args) {
Point p = new Point(1, 2);
System.out.println(p + " " + Kind.CIRCLE); // Point[x=1, y=2] CIRCLE
Visitor v = q -> System.out.println(q.x());
v.visit(p); // 1
}
}This is also why a nested enum or record needs no outer.new syntax. You create it directly, as in new Point(1, 2).
A class declared inside an interface is implicitly public and static, like every other member of an interface.
Local classes: no access modifiers, no static
A local class is declared in a method, constructor, or initializer block. Its scope is the block that contains it, so access modifiers make no sense, and the compiler rejects them:
public,protected,private, andstaticare all illegal on a local class declaration.finalandabstractare allowed.
Since Java 16, a local class may declare static members, as inner classes may.
Java 16 also allows local records, local enums, and local interfaces. All three are implicitly static. A local record is a convenient way to group a few values for the duration of one method:
import java.util.List;
public class LocalRecord {
static void report(List<String> words, int min) {
record Pair(String word, int len) {
boolean longerThan(int n) { return len > n; }
}
for (String w : words) {
Pair p = new Pair(w, w.length());
if (p.longerThan(min)) {
System.out.println(p);
}
}
}
public static void main(String[] args) {
report(List.of("fig", "pear", "banana"), 3);
// Pair[word=pear, len=4]
// Pair[word=banana, len=6]
}
}Notice that min is passed as an argument to longerThan. Writing len > min inside the record would not compile. A local record is static, so it cannot capture the enclosing method's local variables or the enclosing instance. An ordinary local class can capture both, as the earlier chapter on variable capture showed.
Anonymous classes: no constructor, but initializers
An anonymous class has no name, so it cannot declare a constructor. A constructor must share the class's name. The rules for what it can contain follow from that:
- It can declare fields, methods, instance initializer blocks, and (since Java 16) static members.
- It cannot take access modifiers,
static, orabstract. The declaration is part of anewexpression, so there is nowhere to put modifiers. - It extends one class or implements one interface, never both.
new Base() implements Extra {}is not legal syntax.
To pass values to the superclass, put arguments in the new expression. To run setup code, use an instance initializer:
public class AnonymousInit {
static abstract class Shape {
final String name;
Shape(String name) { this.name = name; }
abstract double area();
}
public static void main(String[] args) {
Shape sq = new Shape("square") {
private final double side;
{ side = 3; } // instance initializer replaces a constructor
@Override
double area() { return side * side; }
};
System.out.println(sq.name + " " + sq.area()); // square 9.0
}
}The argument "square" goes to the Shape(String) constructor. The initializer block runs after the superclass constructor finishes and assigns the final field side.
Summary table
| Kind | Static members | Constructors | Access modifiers on declaration | Can use outer instance members |
|---|---|---|---|---|
| Static nested class | Yes | Yes | All | No |
| Inner class | Yes (Java 16+) | Yes | All, but not `static` | Yes |
| Local class | Yes (Java 16+) | Yes | None; `final` and `abstract` only | Yes, in an instance context |
| Local record, enum, interface | Yes | Yes (record, enum) | None | No |
| Anonymous class | Yes (Java 16+) | No (use initializers) | None | Yes, in an instance context |
| Nested record, enum, interface | Yes | Yes (record, enum) | All (implicitly static) | No |
Common compile errors
| Error cause | Example | Fix |
|---|---|---|
| Static member in an inner class on Java 15 or older | `class Inner { static int n; }` | Upgrade to Java 16+, or move the member to a static nested class |
| Access modifier on a local class | `private class Helper {}` inside a method | Remove the modifier |
| Constructor in an anonymous class | `new Task() { Task() {} }` | Use an instance initializer block |
| Nested class named like its outer class | `class A { class A {} }` | Rename the nested class |
| Instance member used from a nested record | `record R() { int f() { return outerField; } }` | Pass the value as a parameter or component |
Which rule applies?
Exercise
The following code compiles on Java 17 but fails on Java 11. Why does it fail, and what is one way to make it compile on both versions? public class Outer { class Inner { static int total = 0; static void add(int n) { total += n; } } }
Show answer
Before Java 16, an inner class could not declare static members, except constants (static final fields initialized with compile-time constants). total is not final, and add is a static method, so Java 11 rejects both. One fix is to make Inner a static nested class by writing static class Inner, which may declare any static members. Another is to move total and add into Outer itself.
Exercise
A method contains a local record record Point(int x, int y) {}. The method also has a parameter int scale. Can a method inside Point read scale? What if Point were a local class instead of a record?
Show answer
No for the record. A local record is implicitly static, so it cannot capture the enclosing method's local variables or parameters. Pass scale as a method parameter or make it a record component. If Point were an ordinary local class, it could read scale, provided scale is final or effectively final.
Exercise
You need an anonymous subclass of an abstract class whose only constructor takes a String, and you need to set up a field before the first method call. Where do the string and the setup code go?
Show answer
The string goes in the parentheses of the new expression, as in new Base("text") { ... }, and is passed to the superclass constructor. The setup code goes in an instance initializer block (a bare { ... }) inside the class body, because an anonymous class cannot declare a constructor.