Sub topic 1
Why nest classes, and the four kinds
Java lets you declare a class inside another class, or even inside a method body. This chapter explains why you would do that, names the four kinds of nested class, and shows how to recognize each one. Later chapters cover each kind in detail. Here you build the map.
Prerequisites
This chapter assumes you can already do the following:
- Write, compile, and run basic Java classes with a
mainmethod. - Use the four access levels:
public,protected, package-private (no modifier), andprivate. - Read interfaces, abstract classes, and
@Overridewithout trouble. - Tell instance members from
staticmembers, and know that astaticmember belongs to the class rather than to an object. - Recognize
RunnableandComparator<T>, and read simple generic types.
Why nest classes at all
A top-level class lives in its own file (or at least at package level) and is visible to its whole package, or to everyone if it is public. Many classes do not deserve that exposure. They exist only to help one other class. Nesting gives you four practical benefits.
- Tighter scope. A helper class that only one class uses can be declared
private, so no other code can see or depend on it. - Closer code. The helper sits next to the code that uses it, so a reader does not have to jump between files.
- Shared private access. A nested class and its enclosing class can read each other's
privatemembers. This lets you split a design into several classes without making fields package-visible just to share them. - Less boilerplate for one-off behavior. Instead of declaring a named top-level class for a single
RunnableorComparator, you can write the implementation at the place where you use it.
The term nested class covers every class declared inside another class or inside a method. The class that contains it is the enclosing class (or outer class).
The four kinds
Java has four kinds of nested class. They differ in where they are declared and in whether instances carry a reference to an enclosing object.
| Kind | Where it is declared | `static`? | Has a name? | Holds a reference to an outer instance? |
|---|---|---|---|---|
| Static nested class | As a member of the class body | Yes | Yes | No |
| Inner class | As a member of the class body | No | Yes | Yes |
| Local class | Inside a method, constructor, or initializer block | No | Yes (visible only in that block) | Yes, if the block is non-static |
| Anonymous class | In an expression, at the point of use | No | No | Yes, if the surrounding code is non-static |
Static nested classes and inner classes are both member classes, because they are members of the enclosing class, just like fields and methods. The only syntactic difference between them is the word static. That one keyword changes how instances are created and what they can see.
Local and anonymous classes are the two kinds that live inside code. Their scope is limited to the block or expression where they appear.
Some sources use "inner class" for all non-static nested classes, which includes local and anonymous ones. The Java Language Specification uses it this way. This tutorial follows that definition when it speaks about the compiler, and says "inner member class" when it needs to be specific.
All four in one file
The following program declares one of each kind inside a class named Outer. Read it first, then run it.
import java.util.function.IntSupplier;
public class Outer {
private int value = 10;
// 1. Static nested class: no Outer instance needed
static class StaticNested {
int twice(int n) {
return n * 2;
}
}
// 2. Inner class: every instance belongs to one Outer
class Inner {
int read() {
return value; // reads Outer's private field directly
}
}
// 3. Local class: declared inside a method
IntSupplier makeSupplier(int offset) {
class Local implements IntSupplier {
@Override
public int getAsInt() {
return value + offset;
}
}
return new Local();
}
// 4. Anonymous class: declared and instantiated in one expression
Runnable makeAnonymous() {
return new Runnable() {
@Override
public void run() {
System.out.println("value = " + value);
}
};
}
public static void main(String[] args) {
Outer o = new Outer();
System.out.println(new Outer.StaticNested().twice(4)); // 8
System.out.println(o.new Inner().read()); // 10
System.out.println(o.makeSupplier(5).getAsInt()); // 15
o.makeAnonymous().run(); // value = 10
}
}Look at how each kind is created:
new Outer.StaticNested()needs noOuterobject. The nested class is reached through the outer class's name, as with any static member.o.new Inner()names anOuterobject,o, on the left ofnew. An inner instance cannot exist without one. The next chapters explain this syntax fully.new Local()appears insidemakeSupplier, the only place where the nameLocalis visible.new Runnable() { ... }creates an object of a class that has no name. The braces afterRunnable()are the class body.
Local uses the parameter offset, and the anonymous class uses the field value. Local and anonymous classes can read variables from the code around them. The rules for that are in the chapter on capturing effectively final variables.
Which one has access to what
The kinds also differ in what they can reach in the enclosing class.
- A static nested class can use the enclosing class's
staticmembers directly, including private ones. It cannot use the enclosing class's instance fields without an explicit object, for exampleouter.value. - An inner class can use all members of its enclosing instance directly, including private instance fields and methods.
- A local or anonymous class can use everything its enclosing scope can use. In an instance method, that includes the enclosing instance's members. It can also use local variables and parameters that are final or effectively final.
In the other direction, the enclosing class can reach the private members of its nested classes. The chapter on private access explains why this works.
A decision flow in miniature
You can classify any nested class by asking two questions about the declaration. The diagram below shows the order.
Choosing a kind: a first rule of thumb
The full decision guide comes at the end of the tutorial. For now, use this order of preference:
- Static nested is the default for a helper that does not need an outer object. A builder or a simple node record are typical examples. If the nested class never touches the enclosing instance, make it
static. - Inner fits when each instance of the helper conceptually belongs to one outer object and needs its fields, such as an iterator over a collection's internal array.
- Local is rare. Use it when a named class is needed only inside one method, for example because you create several instances of it there.
- Anonymous suits a one-off implementation of an interface or an abstract class at the call site. For an interface with a single abstract method, a lambda is often shorter.
Choosing static first matters for a reason beyond style. An inner instance silently keeps its enclosing object reachable, which can hold memory longer than you expect. A later chapter covers that retention.
Common mistakes at this stage
- Forgetting that an inner class needs an outer object. Writing
new Inner()from astaticmethod likemain, with noOuterobject, is a compile-time error. Useo.new Inner()or move the creation into an instance method. - Calling every nested class "inner". The word has a specific meaning in the language rules. A static nested class is not an inner class.
- Nesting for the sake of it. If a class is used by several unrelated classes, make it top-level. Nesting is for classes that belong to one owner.
What compilation does with them
The compiler turns every nested class into its own .class file. The names combine the outer class name and the nested name with a $. For the sample program you would see files such as:
Outer.classOuter$StaticNested.classOuter$Inner.classOuter$1Local.classOuter$1.class
The JVM sees these as ordinary classes. The nesting relationship is recorded as extra metadata, which is why the language-level rules (such as private access and the outer reference) are enforced by the compiler. A later chapter on the compiled form walks through this.
Summary
- Nest a class to limit its scope, keep it near its only user, share private access, or avoid a one-off top-level class.
- There are four kinds: static nested, inner, local, and anonymous.
- Static nested and inner classes are members. They differ only by the
statickeyword, which decides whether instances need an outer object. - Local and anonymous classes are declared in code and can read effectively final variables from the surrounding scope.
- When unsure, start with
staticand remove it only when the class needs the enclosing instance.
Exercise
A class Library has a private List<Book> books field. You need a class BookIterator that walks books and is used only by Library. Another class, Shelf, is a plain data holder with two fields that never reads anything from Library. Which kind of nested class fits each, and why?
Show answer
BookIterator fits an inner (non-static member) class, ideally private, because each iterator belongs to one Library object and reads its private books field directly. Shelf fits a static nested class, because it needs no Library instance and should not carry a hidden reference to one.
Exercise
Is the following declaration a static nested class, an inner class, a local class, or an anonymous class? Name the deciding feature. Comparator<String> byLength = new Comparator<String>() { public int compare(String a, String b) { return a.length() - b.length(); } };
Show answer
It is an anonymous class. The deciding feature is that the class body follows new Comparator<String>() in an expression and the class has no name.