Codectionary / Developer documentation / Java

Static Nested Classes

Group a helper type with its owner without requiring an enclosing object instance.

What it is and why to use it

A nested class keeps a closely related helper type inside another class’s namespace. Declaring it static means its instances do not carry an implicit reference to an instance of the outer class. It is useful for small result objects, builders and implementation details with a clear owner.

How it works

A static nested class is still a class: its objects can have their own fields and constructors. From outside Main, its name would be Main.Score. Unlike a non-static inner class, constructing it does not require an outer Main object. It cannot directly access outer instance fields without an explicit object reference.

Common mistakes and limitations

static on the nested class does not turn all its fields into static fields. Avoid making helpers public solely for convenience if they are an implementation detail.

Try it and keep learning

Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.

Syntax

static class Score { /* fields and methods */ }

Examples

Static Nested Classes

Complete Main.java example — Java 17 or later, without preview features.

public class Main {
  static class Score {
    private final int points;
    Score(int points) { this.points = points; }
    int doubled() { return points * 2; }
  }

  public static void main(String[] args) {
    Score score = new Score(6);
    System.out.println(score.doubled());
  }
}
  1. Score belongs to Main’s namespace but new Score does not create or need an outer Main instance.
  2. The constructor stores 6 in this Score object’s points field.
  3. doubled reads the field and returns 12. This keeps a small helper near its consumer while giving it an ordinary object lifecycle.
  4. Expected output: 12

Best practices

  • Use the narrowest useful visibility.
  • Prefer a top-level type if several unrelated classes need the same concept.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading