Java Local, Anonymous and Static Nested Classes
Learn the remaining kinds of Java nested classes: local classes inside methods, capturing effectively final variables, anonymous inner classes and their syntax, var with anonymous types, double brace initialization, the getEnclosingClass trick, and static nested classes and records.
kvi5hnuCode Sprout team member12 min readOn this page
The previous article introduced inner classes declared as members of another class. Java has three more ways to nest a class: local classes inside a method, anonymous classes without a name, and static nested classes without an outer object. Here's how they fit together:

The Java Language Specification uses the term nested class for any class declared inside another class or interface, static class for a (necessarily nested) static class, and inner class for a nested class that isn't static.
Local Inner Classes
Look carefully at the TalkingClock example, and you'll see that the name of the type TimePrinter is needed only once: when an object of that type is created in the start method.
In that situation, you can define the class locally in a single method:
public void start() {
class TimePrinter implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("At the tone, the time is "
+ Instant.ofEpochMilli(event.getWhen()));
if (beep) Toolkit.getDefaultToolkit().beep();
}
}
var listener = new TimePrinter();
var timer = new Timer(interval, listener);
timer.start();
}
Local classes are never declared with an access specifier (public or private). Their scope is always restricted to the block in which they're declared.
Local classes have one great advantage: they're completely hidden from the outside world. Not even other code in the TalkingClock class can access them. No method except start knows about the TimePrinter class. (Since Java 16, you can also declare local records, enums and interfaces, which are implicitly static, so they can't use the enclosing method's variables.)
Accessing Variables from Outer Methods
Local classes have another advantage over other inner classes. Not only can they access the fields of their outer classes; they can even access local variables! Those variables must be effectively final: they may never change once assigned, just like variables captured by lambdas.
Here's a typical example. Let's move the interval and beep parameters from the TalkingClock constructor to the start method:
public void start(int interval, boolean beep) {
class TimePrinter implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("At the tone, the time is "
+ Instant.ofEpochMilli(event.getWhen()));
if (beep) Toolkit.getDefaultToolkit().beep();
}
}
var listener = new TimePrinter();
var timer = new Timer(interval, listener);
timer.start();
}
TalkingClock no longer needs a beep field. The local class simply refers to the beep parameter of start.
Maybe that's not surprising. The line if (beep) . . . is, after all, inside the start method, so why shouldn't it see beep? To see the subtle issue, follow the flow of control:
- The
startmethod is called. - The variable
listeneris initialized by calling the constructor of the inner classTimePrinter. - The
listeneris passed to theTimerconstructor, the timer starts, andstartexits. At this point, thebeepparameter variable no longer exists. - A second later,
actionPerformedexecutesif (beep) . . ..
For actionPerformed to work, TimePrinter must have copied the value of beep before the parameter went away. That's exactly what happens. The compiler synthesizes the name TalkingClock$1TimePrinter for the local class, and javap -private shows:
class TalkingClock$1TimePrinter implements java.awt.event.ActionListener {
final boolean val$beep;
TalkingClock$1TimePrinter();
public void actionPerformed(java.awt.event.ActionEvent);
}
When an object is created, the current value of beep is stored in the val$beep field. The compiler passes that value to the constructor as a hidden extra argument. Plain javap doesn't show the hidden parameters, but javap -v does: the constructor's real descriptor is (LTalkingClock;Z)V, an outer object plus a boolean. The field persists after the local variable goes out of scope. That copy is also why the variable must be effectively final: if it could change later, the copy and the original would disagree. (In this output there's no this$0, since the class never uses the TalkingClock object; the Java 18 optimization from the previous article applies here too.)
Anonymous Inner Classes
With local classes, you can often go one step further. If you want only a single object of the class, you don't even need to give the class a name. Such a class is called an anonymous inner class:
public void start(int interval, boolean beep) {
var listener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("At the tone, the time is "
+ Instant.ofEpochMilli(event.getWhen()));
if (beep) Toolkit.getDefaultToolkit().beep();
}
};
var timer = new Timer(interval, listener);
timer.start();
}
This syntax is cryptic indeed. It means: create a new object of a class that implements the ActionListener interface, where the required method actionPerformed is the one defined inside the braces { }.
In general, the syntax is
new SuperType(construction arguments) {
inner class methods and data
}
SuperTypecan be an interface, such asActionListener; then the anonymous class implements that interface.SuperTypecan be a class; then the anonymous class extends it.
An anonymous class can't have constructors, because a constructor's name must be the class name, and the class has no name. Instead, the construction arguments are passed to the superclass constructor. In particular, when an anonymous class implements an interface, it can't have construction arguments, but you must still supply empty parentheses:
new InterfaceType() {
methods and data
}
Look carefully to see the difference between constructing an object of a class and constructing an object of an anonymous class extending it:
var queen = new Person("Mary");
// a Person object
var count = new Person("Dracula") { . . . };
// an object of an anonymous class extending Person
If the closing parenthesis of the argument list is followed by an opening brace, an anonymous class is being defined.
Even though an anonymous class can't have constructors, it can have an object initialization block:
var count = new Person("Dracula") {
{ initialization }
. . .
};
Anonymous classes versus lambdas
For many years, Java programmers routinely used anonymous classes for event listeners and other callbacks. Today you're better off with a lambda. The start method shrinks to:
public void start(int interval, boolean beep) {
var timer = new Timer(interval, event -> {
System.out.println("At the tone, the time is " + Instant.ofEpochMilli(event.getWhen()));
if (beep) Toolkit.getDefaultToolkit().beep();
});
timer.start();
}
Anonymous classes are still the right tool when you need more than a lambda can do:
| Need | Anonymous class | Lambda |
|---|---|---|
| Implement an interface with several abstract methods | Yes | No |
Extend a class (possibly abstract), e.g. new AbstractList<>() { ... } | Yes | No |
| Keep state in fields | Yes | No (only captured values) |
this refers to | The anonymous object | The enclosing object |
| Generates a separate class file | Yes (Outer$1.class) | No (created at runtime) |
var and anonymous types
If you store an anonymous class instance in a variable declared with var, the variable knows about the added methods and fields:
var bob = new Object() { String name = "Bob"; };
System.out.println(bob.name);
If you declared bob as Object, then bob.name wouldn't compile. The object constructed with new Object() { String name = "Bob"; } has the type "Object with a String name field". That's a non-denotable type, a type you can't write in Java syntax. The compiler understands it nonetheless and uses it as the type of bob. It's a curiosity; for real code, a local record is clearer.
Double brace initialization
The following trick, called double brace initialization, exploits the anonymous class syntax. Suppose you want to construct an array list and pass it to a method:
var friends = new ArrayList<String>();
friends.add("Omar");
friends.add("Lena");
invite(friends);
If you don't need the list again, it would be nice to make it anonymous. Here's how:
invite(new ArrayList<String>() {{ add("Omar"); add("Lena"); }});
The outer braces make an anonymous subclass of ArrayList. The inner braces are an object initialization block.
In practice, this trick is rarely useful and has real costs: it creates an extra class each time it's used, it captures the enclosing this (a potential memory leak), and the object isn't a plain ArrayList. More likely than not, invite accepts any List<String>, and you can simply pass List.of("Omar", "Lena").
Finding the current class in a static method
When writing log or debug messages, you often want the name of the current class:
System.err.println("Something awful happened in " + getClass());
That fails in a static method: getClass() calls this.getClass(), and a static method has no this. Use this expression instead:
new Object(){}.getClass().getEnclosingClass() // gets class of static method
new Object(){} makes an object of an anonymous subclass of Object, and getEnclosingClass returns its enclosing class, the class containing the static method. Modern alternatives are MethodHandles.lookup().lookupClass() (no extra class), or StackWalker.getInstance(RETAIN_CLASS_REFERENCE).getCallerClass() from a helper method.
Static Nested Classes
Occasionally you want to nest one class inside another, but the nested class doesn't need a reference to the outer object. You suppress that reference by declaring the nested class static.
Here's a typical example. In an ArrayAlg class, a method finds a range of elements in an array, and needs to return the start and end of the range. We define a class Range that holds two values:
class Range {
private int from;
private int to;
public Range(int from) { . . . }
public void extend() { . . . }
. . .
}
Range is an exceedingly common name, and in a large project another programmer may well have had the same bright idea and defined another Range class in the same package. We avoid the clash by making Range a public nested class inside ArrayAlg. Then the class is known to the public as ArrayAlg.Range:
ArrayAlg.Range r = ArrayAlg.longestRun(numbers);
Unlike the inner classes in earlier examples, a Range object doesn't need a reference to any other object. So we declare the nested class static:
class ArrayAlg {
public static class Range {
. . .
}
. . .
}
A static class is exactly like an inner class, except that its objects don't have a reference to the outer object that created them. Here we must use a static class, because the Range objects are constructed inside a static method:
public static Range longestRun(double[] values) {
. . .
Range current = new Range(. . .);
. . .
if (. . .) longest = current;
. . .
return longest;
}
Had Range not been static, the compiler would have flagged the constructor call as an error: there's no implicit ArrayAlg object available to initialize the inner object.
Use a static class whenever a nested class doesn't need to access an outer object. Joshua Bloch's Effective Java puts it as "favor static member classes over nonstatic".
Range is deliberately mutable here. It might be better to make it immutable and declare it as a record, which is automatically static. Likewise:
- records, interfaces and enums declared inside a class or interface are automatically static,
- classes declared inside an interface are automatically static and public,
- since Java 16, you can declare static classes inside inner classes (previously forbidden).
Here's everything from this article in one program, including the longestRun algorithm. A run is a sequence of repeating adjacent values: in 1 2 2 3 3 3 4 4, the longest run is 3 3 3, at indexes 3 up to (excluding) 6.
import java.time.Instant;
import java.util.*;
public class Solution {
public static void main(String[] args) {
var clock = new TalkingClock();
clock.startLocal(1000, true, 2);
clock.startAnonymous(500, false, 2);
clock.startLambda(250, 2);
// var keeps the anonymous type, so added fields are usable
var bob = new Object() { String name = "Bob"; int age = 42; };
System.out.println(bob.name + " " + bob.age);
// double brace initialization: an anonymous ArrayList subclass (avoid)
var friends = new ArrayList<String>() {{ add("Omar"); add("Lena"); }};
System.out.println(friends + " " + friends.getClass().getName()
+ " vs " + List.of("Omar", "Lena"));
// anonymous subclasses break getClass()-based equals
var p1 = new Point(1, 2);
var p2 = new Point(1, 2) { }; // almost, but not quite, a Point
System.out.println(p1.equals(p2) + " " + p2.getClass().getName());
// the current class name, even in a static method
System.out.println("in " + new Object(){}.getClass().getEnclosingClass().getSimpleName());
// static nested class
double[] numbers = { 1, 2, 2, 3, 3, 3, 4, 4 };
ArrayAlg.Range r = ArrayAlg.longestRun(numbers);
System.out.println("from = " + r.getFrom() + ", to = " + r.getTo());
System.out.println(ArrayAlg.minmax(numbers));
}
}
class TalkingClock {
private static final Instant START = Instant.parse("2026-11-13T09:00:00Z");
/** A local class: visible only inside this method, captures interval and beep. */
public void startLocal(int interval, boolean beep, int ticks) {
class TimePrinter {
void tick(Instant when) {
System.out.println("[local] At the tone, the time is " + when + (beep ? " BEEP" : ""));
}
}
var listener = new TimePrinter();
simulate(interval, ticks, listener::tick);
System.out.println(" local class name: " + TimePrinter.class.getName());
}
/** An anonymous class implementing an interface. */
public void startAnonymous(int interval, boolean beep, int ticks) {
var listener = new TickListener() {
private int count; // anonymous classes can have state
{ System.out.println(" [anonymous] initialization block runs"); }
@Override
public void tick(Instant when) {
count++;
System.out.println("[anonymous #" + count + "] " + when + (beep ? " BEEP" : ""));
}
};
simulate(interval, ticks, listener);
System.out.println(" anonymous class name: " + listener.getClass().getName());
}
/** The modern way: a lambda. */
public void startLambda(int interval, int ticks) {
simulate(interval, ticks, when -> System.out.println("[lambda] " + when));
}
private void simulate(int interval, int ticks, TickListener listener) {
Instant t = START;
for (int i = 0; i < ticks; i++) listener.tick(t = t.plusMillis(interval));
}
}
interface TickListener {
void tick(Instant when);
}
class Point {
private final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override public boolean equals(Object other) {
if (other == null || getClass() != other.getClass()) return false;
var p = (Point) other;
return x == p.x && y == p.y;
}
@Override public int hashCode() { return Objects.hash(x, y); }
}
class ArrayAlg {
/** A range of index values: a static nested class, no outer reference. */
public static class Range {
private final int from;
private int to;
/** Constructs a range of length 1. */
public Range(int from) { this.from = from; this.to = from + 1; }
/** Extends this range by one element. */
public void extend() { to++; }
public int getFrom() { return from; }
/** Gets the first index past the end of the range. */
public int getTo() { return to; }
public int length() { return to - from; }
}
/** An immutable alternative: records are implicitly static. */
public record Pair(double first, double second) { }
/**
* A "run" is a sequence of repeating adjacent values. For example, in
* 1 2 3 3 3 4 4, the runs are (trivially) 1 and 2, then 3 3 3 and 4 4.
* Returns the range of the longest run.
* @param values an array of length at least 1
*/
public static Range longestRun(double[] values) {
Range longest = new Range(0);
Range current = new Range(0); // fine: Range is static
for (int i = 1; i < values.length; i++) {
if (values[i] == values[i - 1]) current.extend();
else {
if (longest.length() < current.length()) longest = current;
current = new Range(i);
}
}
if (longest.length() < current.length()) longest = current;
return longest;
}
public static Pair minmax(double[] values) {
double min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY;
for (double v : values) { min = Math.min(min, v); max = Math.max(max, v); }
return new Pair(min, max);
}
}
[local] At the tone, the time is 2026-11-13T09:00:01Z BEEP
[local] At the tone, the time is 2026-11-13T09:00:02Z BEEP
local class name: TalkingClock$1TimePrinter
[anonymous] initialization block runs
[anonymous #1] 2026-11-13T09:00:00.500Z
[anonymous #2] 2026-11-13T09:00:01Z
anonymous class name: TalkingClock$1
[lambda] 2026-11-13T09:00:00.250Z
[lambda] 2026-11-13T09:00:00.500Z
Bob 42
[Omar, Lena] Solution$2 vs [Omar, Lena]
false Solution$3
in Solution
from = 3, to = 6
Pair[first=1.0, second=4.0]
Note the generated class names: TalkingClock$1TimePrinter for the local class, TalkingClock$1, Solution$2 and Solution$3 for anonymous classes, numbered in order of appearance in each top-level class.
Common questions
Anonymous class or lambda?
Use a lambda for a functional interface whenever the body is short. Use an anonymous class when you need state (fields), several methods, a non-functional interface, an abstract class, or when this must refer to the object itself.
Is double brace initialization a good idea?
No. It creates an extra class, captures the enclosing object (a possible memory leak), and can break equals and serialization. Use List.of(...), Map.of(...) or a plain new ArrayList<>() followed by add calls.
What is the difference between a local class and a local record?
A local class is an inner class. It can capture effectively final local variables and the enclosing this. A local record (Java 16) is implicitly static, so it can't use the enclosing method's variables or instance. It's ideal for intermediate results inside a method.
Can a static nested class access the outer class's private static members? Yes. Nested classes are nestmates of their outer class, so they can use its private static fields and methods. They just have no outer instance to access instance members through.
How do I get the current class name in a static method?
MethodHandles.lookup().lookupClass().getSimpleName() works without creating extra classes. The older new Object(){}.getClass().getEnclosingClass() trick also works, but it generates an anonymous class for every place you use it.
Summary
- A local class is declared inside a method, has no access modifier, and is invisible outside its block. It can access fields of the outer object and effectively final local variables, whose values are copied into synthetic
val$fields. - An anonymous class,
new SuperType(args) { body }, defines and instantiates a class in one expression. It extends a class or implements an interface, has no constructors (use initialization blocks), and passes arguments to the superclass constructor. - Prefer lambdas for functional interfaces. Use anonymous classes for multi-method interfaces, abstract classes, or when state is needed.
vargives access to an anonymous object's added members. Avoid double brace initialization; useList.of.- A static nested class has no outer object reference. Use one whenever the nested class doesn't need outer instance state. Nested records, enums and interfaces are implicitly static.
Practice Questions
Why can't a local class modify a local variable of the enclosing method?
The local class works with a copy of the value, stored in a synthetic field when the object is created. If the variable could change, the copy and the variable would disagree, so Java requires it to be effectively final.
What's printed? Runnable r = new Runnable() { public void run() { System.out.println(this.getClass().getName()); } }; r.run(); (inside class Solution)
Solution$1. Inside an anonymous class, this is the anonymous object, whose compiler-generated class is Solution$1. In a lambda written in an instance method, this would be the enclosing Solution object, so the same line would print Solution. (Comparing this.getClass() == Solution.class directly wouldn't even compile: javac reports incomparable types, because a Class of the anonymous subtype can never equal Class<Solution>.)
Can an anonymous class have a constructor? How do you initialize it?
No, because it has no name. Pass arguments to the superclass constructor in new SuperType(args), and use an instance initialization block { ... } for additional setup.
A builder class nested in Pizza never uses a Pizza instance. Should it be static?
Yes. It doesn't need the outer object, and making it static lets client code write new Pizza.Builder() without a Pizza instance. It also avoids a hidden reference.
Replace new ArrayList<String>() {{ add("a"); add("b"); }} with idiomatic code, and give two reasons why.
List.of("a", "b"), or new ArrayList<>(List.of("a", "b")) if it must be mutable. Double brace initialization creates an extra anonymous class and may capture the enclosing this, which can leak memory.
Previous: Java Inner Classes: Accessing Outer Object State
Next: Java ServiceLoader: Loading Pluggable Service Implementations
Related reading
- Java Inner Classes: Accessing Outer Object State
- Java Inheritance Design Hints: Best Practices for Class Hierarchies
- Java Reflection: Analyzing Classes and Inspecting Objects at Runtime
- Java Reflection: The Class Class, Exceptions Primer and Loading Resources
- Java Sealed Classes and Interfaces: Controlling Inheritance

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.