Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

Compare static nested classes, inner classes, local classes and anonymous classes. When would you choose each?

A static nested class is an ordinary class placed inside another one for organisation; it has no link to an outer object, which makes it the right default for helpers such as builders and entries. An inner class is non-static and holds a hidden reference to an outer instance, so it can use that instance's fields. A local class is declared inside a method and can capture effectively final local variables, and an anonymous class is a local class with no name, created in one expression, which lambdas have mostly replaced for functional interfaces.

Why this question is asked

Java has four ways to declare a class inside something else, and they differ in one thing that matters a lot in practice: what each one secretly holds on to. Choosing the wrong one costs memory, causes leaks and makes code harder to read, which is why interviewers like to ask for the comparison and for a rule of thumb. In this answer, we will look at each kind with a small example, see what the compiler adds behind the scenes, compare them side by side, and end with how to choose.

1Static Nested Classes

A static nested class is declared with static inside another class. It behaves like any top-level class, except that its name is scoped by the outer class (Order.Builder) and it can access the outer class's private static members. It has no reference to any outer object, because there might not be one.

Java
public final class Order {
private final String id;
private final int qty;
private Order(Builder b) { this.id = b.id; this.qty = b.qty; }
public static final class Builder { // no hidden link to an Order
private String id;
private int qty;
public Builder id(String id) { this.id = id; return this; }
public Builder qty(int qty) { this.qty = qty; return this; }
public Order build() { return new Order(this); }
}
}
Order o = new Order.Builder().id("A-1").qty(3).build();

Builders, map entries (HashMap.Node), small result types and private helper structures are typical uses. The nesting says "this belongs with Order" without tying instances together.

2Inner Classes

Drop the static keyword and we get an inner class. Every instance of it is created for one particular outer instance and keeps a reference to it. That is what lets inner code read the outer object's fields directly.

Java
class Playlist {
private final List<String> songs = new ArrayList<>();
class Cursor { // compiler adds a hidden field: final Playlist this$0
private int pos;
String next() { return songs.get(pos++); } // really Playlist.this.songs
}
}
Playlist p = new Playlist();
Playlist.Cursor c = p.new Cursor(); // needs an outer instance

Notice the unusual p.new Cursor() syntax; an inner class cannot exist without an outer object. The hidden reference is the price: as long as a Cursor is alive, its Playlist is alive too. That is right for an iterator that walks its own collection, which is exactly how many JDK iterators are written, and wrong for anything that may outlive the outer object.

3Local and Anonymous Classes

A local class is declared inside a method body. It is visible only in that method, and it can use the method's local variables and parameters as long as they are effectively final, meaning they are never reassigned. The compiler copies their values into the class. If the method is an instance method, a local class also holds this, like an inner class.

An anonymous class is a local class with no name, declared and instantiated in a single expression. It was the standard way to pass behaviour before Java 8.

Java
List<String> filter(List<String> in, int min) {
class LongerThan implements Predicate<String> { // local class, captures min
public boolean test(String s) { return s.length() > min; }
}
return in.stream().filter(new LongerThan()).toList();
}
Comparator<String> byLength = new Comparator<>() { // anonymous class
@Override public int compare(String a, String b) { return Integer.compare(a.length(), b.length()); }
};
Comparator<String> byLength2 = Comparator.comparingInt(String::length); // what we write today

For an interface with a single abstract method, a lambda or method reference says the same thing in one line. Anonymous classes are still needed when we must implement an interface with several methods, extend an abstract class, or keep state in fields. Local classes are rare, but they are useful when a helper type needs a name, several methods or fields, and makes sense in only one method; local records are often an even simpler choice.

4Comparing the Four Side by Side

The table puts the differences in one place. The column that matters most in practice is the second one: whether the class carries a reference to an outer instance.

The four kinds of nested class
KindOuter instance?Can captureTypical use
Static nestedNoouter private static membersbuilders, entries, helper types
InnerYes, hidden this$0all outer membersiterators over their own outer object
LocalYes, in instance methodseffectively final locals, outer membersone-method helper with a name
AnonymousYes, in instance methodseffectively final locals, outer membersmulti-method or abstract-class callbacks
Lambda (for comparison)Only if it uses thiseffectively final localsfunctional interfaces

So the four kinds are really two questions. Does the class need the outer object's state? Only then use an inner class, or a local or anonymous class in an instance method. Does it need a name and reuse? If not, a lambda or an anonymous class keeps it next to where it is used.

5How to Choose

The rule of thumb is to default to a static nested class, and drop static only when the code really needs the outer instance. A static nested class is cheaper, since it has one field fewer per instance, it cannot keep a large outer object alive by accident, and it can be created anywhere without an outer instance, which makes it easy to test. Many style guides and tools, including IntelliJ's inspections and Sonar, suggest making an inner class static when it does not use the outer instance.

For behaviour passed as an argument, prefer a lambda or a method reference, then an anonymous class when a lambda cannot do the job. Keep local classes for the rare helper that is used in one method only.

6Follow-up questions

Why can a local class only capture effectively final variables?

The class gets a copy of the variable's value, because the method's stack frame may be gone by the time the class runs. If the variable could change afterwards, the copy and the original would disagree. Requiring effectively final variables makes the copy indistinguishable from the original, so there is no confusion.

Can an inner class declare static members?

Since Java 16, yes. Earlier versions allowed only static constant variables in inner classes; JEP 395, which delivered records, relaxed the rule so inner classes can declare static members, including static methods and nested records.

Is a nested enum, record or interface static?

Yes, always. Nested enums, records and interfaces are implicitly static, so they never hold an outer instance, whether or not we write the keyword.

7Conclusion

In this answer, we compared the four kinds of nested class. A static nested class is an ordinary class scoped inside another and holds no outer reference; an inner class holds a hidden reference to its outer instance; a local class lives in one method and captures effectively final locals; and an anonymous class is an unnamed local class created in one expression, now mostly replaced by lambdas. The practical rule is to default to static nested classes and use the others only when we need the outer instance or a one-off implementation.

What to say in the interviewAbout 90 seconds aloud

Open with

The four kinds differ mainly in what they hold on to. A static nested class is just a class scoped inside another one; it has no reference to an outer instance, can see the outer class's private static members, and is what I use for builders, map entries and helper types.

Then, if they want more

An inner class, without static, is always created for a specific outer object and keeps a hidden reference to it, the this$0 field, so it can use the outer instance's fields directly; that suits something like an iterator over its own collection, but it also means the inner object keeps the outer one alive.

A local class is declared inside a method, can capture effectively final local variables, and in an instance method also holds this; I rarely need it, and a local record is often simpler.

An anonymous class is an unnamed local class declared and created in one expression; since Java 8, lambdas and method references replace it for functional interfaces, and I keep anonymous classes for interfaces with several methods or for extending an abstract class.

My default is a static nested class, and I only drop static when the code really needs the outer instance, because the hidden reference costs memory and is a common source of leaks.

About this answer

Last updated
12 November 2026
Versions it names
Java 16, Java 8
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Compare static nested classes, inner classes, local classes and anonymous classes. When...": https://scrivio-interview-library.netlify.app/java/classes-and-objects/6139ce8215/