0Pricing
Java Academy · Lesson

Static Nested Classes

Define static nested classes as associated helper types without an enclosing instance reference.

Static Nested Classes is a free Java Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Static Nested Classes

A static nested class is defined inside another class with the static keyword. It has no reference to the enclosing class instance — it is just logically grouped with it.

Declaring a Static Nested Class

Use the outer class name to access the nested class from outside.

class LinkedList<T> {
    private Node<T> head;

    // Static nested class — no outer instance reference
    private static class Node<T> {
        T data;
        Node<T> next;
        Node(T data) { this.data = data; }
    }

    public void addFirst(T item) {
        Node<T> node = new Node<>(item);
        node.next = head;
        head = node;
    }
}

Accessing from Outside

Reference a public static nested class as OuterClass.InnerClass.

class Builder {
    public static class Config {
        public final String host;
        public final int port;
        Config(String host, int port) {
            this.host = host; this.port = port;
        }
    }
}

Builder.Config config = new Builder.Config("localhost", 8080);
System.out.println(config.host + ":" + config.port); // localhost:8080

Static Nested vs Inner

The key difference: static nested classes do NOT have an implicit reference to the outer instance. Inner (non-static) classes DO have such a reference.

class Outer {
    private int x = 10;

    // Static nested: no access to x
    static class StaticNested {
        void doSomething() {
            // System.out.println(x); // compile error — no outer reference!
            System.out.println("Static nested");
        }
    }

    // Inner class: has access to x
    class Inner {
        void doSomething() {
            System.out.println(x); // 10 — can access outer fields
        }
    }
}

Builder Pattern with Static Nested

The classic Builder pattern uses a static nested class so callers do not need an outer instance to create a builder.

class Pizza {
    private final String size, crust;
    private final List<String> toppings;

    private Pizza(Builder b) {
        this.size = b.size; this.crust = b.crust; this.toppings = List.copyOf(b.toppings);
    }

    public static class Builder {
        private String size = "medium", crust = "thin";
        private List<String> toppings = new ArrayList<>();
        public Builder size(String s)    { this.size = s; return this; }
        public Builder crust(String c)   { this.crust = c; return this; }
        public Builder topping(String t) { this.toppings.add(t); return this; }
        public Pizza build()             { return new Pizza(this); }
    }
}

Entry in Maps

Map.Entry is a well-known static nested interface used to iterate key-value pairs.

import java.util.*;

Map<String, Integer> scores = Map.of("Alice", 95, "Bob", 87, "Carol", 92);

for (Map.Entry<String, Integer> entry : scores.entrySet()) {
    System.out.printf("%-10s: %d%n", entry.getKey(), entry.getValue());
}

// Modern: using var
for (var entry : scores.entrySet()) {
    System.out.println(entry.getKey() + " -> " + entry.getValue());
}

Testing with Static Nested Class

In unit tests, a static nested class can hold test fixtures or mock implementations scoped to the test class.

class UserServiceTest {
    // Static nested fake/stub — no outer instance needed
    static class FakeUserRepository implements UserRepository {
        private final Map<Long, User> store = new HashMap<>();

        public void save(User u) { store.put(u.id(), u); }

        public Optional<User> findById(long id) {
            return Optional.ofNullable(store.get(id));
        }
    }

    // @Test methods use FakeUserRepository
    void testFindUser() {
        FakeUserRepository repo = new FakeUserRepository();
        // ...
    }
}

Static Nested for Domain Logic

Group related types together using static nested classes for better organization in domain models.

class Order {
    private final long id;
    private final List<LineItem> items;

    // Static nested — logically belongs to Order, no outer reference needed
    public static class LineItem {
        public final String sku;
        public final int quantity;
        public final double unitPrice;

        public LineItem(String sku, int qty, double price) {
            this.sku = sku; this.quantity = qty; this.unitPrice = price;
        }

        public double total() { return quantity * unitPrice; }
    }

    // ...
}

Comparison: Static Nested vs Top-Level

Prefer a static nested class when a class is used only in the context of the outer class. Use a top-level class when it has broader applicability.

Static Nested with Generics

Static nested classes participate in generics just like top-level classes.

class Pair<A, B> {
    // Static nested with its own type params
    public static class Mutable<X, Y> {
        public X first;
        public Y second;
        public Mutable(X first, Y second) {
            this.first = first; this.second = second;
        }
    }

    public static <X, Y> Mutable<X, Y> mutableOf(X x, Y y) {
        return new Mutable<>(x, y);
    }
}
Pair.Mutable<String, Integer> p = Pair.mutableOf("Alice", 30);
System.out.println(p.first + " is " + p.second); // Alice is 30

Memory Efficiency

Static nested classes do not hold a reference to the outer instance. This avoids accidentally retaining the outer object in memory, which can cause memory leaks in long-lived structures.

Quick Check

What distinguishes a static nested class from an inner (non-static) class?

Recap: Static Nested Classes

Key takeaways:

  • Static nested classes are grouped with the outer class but have no outer instance reference
  • Access from outside: OuterClass.NestedClass
  • No implicit reference means no accidental memory retention of outer instance
  • The Builder pattern commonly uses a static nested Builder class
  • Map.Entry is a well-known static nested interface
  • Prefer static nested when the inner class does not need outer instance access

Frequently asked questions

Is the “Static Nested Classes” lesson free?

Yes — the full text of “Static Nested Classes” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Static Nested Classes”?

Define static nested classes as associated helper types without an enclosing instance reference. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Static Nested Classes” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Static Nested Classes
  2. Inner Classes and Outer Access
  3. Local and Anonymous Classes
  4. Choosing the Right Nesting Strategy
← Back to Java Academy