Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 201 ยท Object-Oriented Programming

Nested, Inner, Local and Anonymous Classes

Learn the four kinds of Java nested classes - static nested, inner, local and anonymous - how they access outer members, when to use each, and the memory pitfall.

So far most of your classes have lived side by side at the top level of a file. Java also lets you declare a class inside another class, or even inside a method. These nested classes keep a helper type right next to the only code that uses it, give it access to private members of its surroundings, and stop it from cluttering the rest of the program.

There are four kinds, and they behave quite differently: static nested classes, inner classes, local classes and anonymous classes. This lesson explains each one, how it can reach the members of the enclosing class, the syntax for creating it, and a memory pitfall that catches experienced developers. By the end you'll know which kind to pick, and when a lambda or a top-level class is better.

The four kinds at a glance

Java
class Outer {
    static class StaticNested { }       // 1. static nested class
    class Inner { }                     // 2. inner class (non-static member)

    void work() {
        class Local { }                 // 3. local class, inside a method
        Runnable r = new Runnable() {   // 4. anonymous class: declared and created at once
            public void run() { }
        };
    }
}
Kind Declared Has an outer instance? Can use outer's instance fields? Name
Static nested as a static member No Only through a reference you pass in Outer.StaticNested
Inner as a non-static member Yes, always Yes, directly Outer.Inner
Local inside a method or block Yes, if the method is an instance method Yes, plus effectively final locals Only inside that block
Anonymous in an expression with new Yes, if created in an instance context Yes, plus effectively final locals None

Inner, local and anonymous classes together are called inner classes in the language specification, because all of them can be tied to an instance of the enclosing class. Every nested class, of any kind, can access the private members of the classes that enclose it, and the enclosing class can access the nested class's private members too.

Static nested classes

A static nested class is an ordinary class that happens to live inside another one. It has no hidden link to an outer object, so you create it like any class, using the outer name as a prefix: new Outer.StaticNested(). Use it when a helper type belongs conceptually to its outer class: Map.Entry, a Node inside a linked list, or a Builder.

Java A builder as a static nested class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Pizza's constructor is private, yet Builder.build() calls it, and Pizza's constructor reads b.size and b.toppings, which are private fields of Builder. Nesting grants that mutual access. Outside code sees one clear entry point, new Pizza.Builder(...), and can't create a half-configured pizza any other way. The builder pattern is covered fully in Creational Design Patterns.

Static nested classes can be private (an implementation detail nobody else may use), package-private, protected or public, just like fields. Nested records, enums and interfaces are always implicitly static.

Inner classes

An inner class (a non-static member class) is bound to a specific instance of the outer class. Every inner object carries a hidden reference to the outer object that created it, so its methods can read and change that object's fields directly, even private ones. This is ideal for objects that are views onto, or helpers for, one particular outer object, such as an iterator over a collection.

Java An inner class that works on its outer object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Inside Cursor, songs and name mean the fields of the Playlist that created the cursor. To create an inner object from outside, you need an outer object: roadTrip.new Cursor(). Writing new Playlist.Cursor() without one is a compile error (an enclosing instance that contains Playlist.Cursor is required).

Outer.this

When an inner class has a member with the same name as an outer member, the inner one wins (it shadows the outer one). Use Outer.this to reach the enclosing object explicitly:

Java
class Counter {
    private int value = 100;

    class Step {
        private int value = 1;

        void apply() {
            Counter.this.value += this.value;   // outer field += inner field
        }
    }
}

this alone is the inner object; Counter.this is the outer one. Since Java 16, inner classes may also declare static members, which used to be forbidden.

Local classes

A local class is declared inside a method (or any block) and is visible only there. Like an inner class it can use the outer object's fields, and in addition it can capture local variables and parameters, as long as they are effectively final (never reassigned after initialization). Use a local class when you need a small named type with several methods, or more than one instance, but only inside one method.

Java A local class capturing method variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The local class uses minLength and requiredSymbol without them being passed in. Behind the scenes, the compiler copies their values into hidden fields of the local object. That's why they must be effectively final: if the method could change minLength later, the copy would silently go stale. Adding minLength++; anywhere in validate makes the code fail with local variables referenced from an inner class must be final or effectively final. Lambdas follow the same rule (Lambda Expressions).

Local classes can't have access modifiers (they're already as private as possible). Local records, enums and interfaces are allowed too, and they are implicitly static, so they can't capture anything (see Records).

Anonymous classes

An anonymous class is declared and instantiated in a single expression. You write new, a class or interface name, constructor arguments, and then a class body in braces. The result is one object of a nameless class that extends that class or implements that interface.

Java Anonymous classes, and lambdas where they fit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Anonymous classes can do several things a lambda can't:

  • Extend a class, including an abstract one, and pass arguments to its constructor (new Alarm("06:30") { ... }). A lambda can only implement a functional interface.
  • Implement an interface with several abstract methods.
  • Hold state in fields, like snoozes.
  • Refer to themselves with this. Inside an anonymous class, this is the anonymous object; inside a lambda, this is the enclosing object.

The compiler gives the class a numbered name such as Main$1, which you'll see in stack traces. For a single-method interface like Comparator or Runnable, a lambda is shorter and clearer, and it's the modern choice. Reach for an anonymous class when you need one of the abilities above, or prefer a named class if the body grows beyond a few lines.

The hidden outer reference: a memory pitfall

An inner (or anonymous, or local) object created in an instance method keeps the outer object reachable through its hidden reference. If the inner object lives longer than you'd expect (stored in a cache, registered as a listener, handed to another thread), the whole outer object can't be garbage collected, along with everything it references.

Java Seeing the hidden reference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Using reflection, you can see the synthetic field this$0 that the compiler adds to Inner, while Nested has none. Even after outer = null, the 10 MB buffer stays in memory as long as inner is alive. (Since JDK 18, javac leaves the field out when an inner class never uses its outer instance, but you still need an outer object to create it, and you shouldn't depend on that optimization.)

The rule that follows is simple: make member classes static unless they really need the outer instance. It saves memory, avoids leaks, makes the class easier to create and test, and documents the intent. The Memory and Garbage Collection lesson shows other common leaks.

Choosing the right kind

  • Static nested class: the default for a helper type that belongs to one class: builders, nodes, entries, private implementation classes, nested records and enums.
  • Inner class: only when each instance must work on one specific outer object, such as an iterator or a view over the outer object's data.
  • Local class: a named helper with several methods or multiple instances, needed inside a single method. Fairly rare in modern code.
  • Anonymous class: a one-off implementation that must extend a class, implement several methods or keep state. Otherwise, use a lambda.
  • Top-level class: when the type is useful on its own, or when nesting makes the file hard to read. Don't nest just because you can.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given class Outer { class Inner {} }, which expression creates an Inner object from a static method?

    An inner class needs an enclosing instance, so you create an Outer first and then use outer.new Inner(). The other forms don't compile (or don't exist).
  2. 2. Which kind of nested class does NOT hold a reference to an outer instance?

    A static nested class is independent of any outer object. The other kinds created in an instance context are tied to the enclosing object.
  3. 3. A local class reads the method parameter limit, and later in the method you write limit = 0;. What happens?

    Local and anonymous classes (and lambdas) may only capture effectively final variables. Reassigning limit makes it no longer effectively final.
  4. 4. Inside an anonymous class's method, what does this refer to?

    An anonymous class is a real class, so this means its own instance. In a lambda, by contrast, this refers to the enclosing object.
  5. 5. Why is it usually best to declare member classes static when possible?

    Non-static inner objects hold a hidden reference to their outer object, which can keep large objects from being garbage collected. Static nested classes have no such link.

Summary

  • Java has four nested class kinds: static nested, inner (non-static member), local (inside a block) and anonymous (declared in a new expression).
  • Every nested class can access the private members of its enclosing classes, and vice versa.
  • Static nested classes have no outer instance; create them with new Outer.Nested(). Use them by default for helpers, builders and nodes.
  • Inner objects are tied to an outer object (outer.new Inner()), use its fields directly and reach it explicitly with Outer.this.
  • Local and anonymous classes can capture effectively final local variables; anonymous classes can extend classes, keep state and use this for themselves.
  • Prefer lambdas for single-method interfaces, and static nested classes over inner classes unless you need the outer instance, to avoid memory leaks.

Next: The Object Class: equals, hashCode and toString, where you'll look at the methods every Java class inherits and how to override them correctly.