Sub topic 6
Local classes declared inside methods
This chapter assumes you can write classes and interfaces, know the difference between instance and static members, and have seen static nested and inner member classes. A local class is a named class declared inside a block of code, usually a method body. It sits between an inner member class and an anonymous class. It has a name, a constructor, and any number of fields and methods, but only the surrounding block can see it.
Where a local class can appear
You can declare a local class in any block that can hold statements:
- a method body
- a constructor body
- an instance or static initializer block
- the body of a lambda expression
- a nested block, such as the body of an
iforfor
Here is the smallest useful case.
public class Greeters {
static Runnable makeGreeter(String name) {
class Greeter implements Runnable {
@Override
public void run() {
System.out.println("Hello, " + name);
}
}
return new Greeter();
}
public static void main(String[] args) {
makeGreeter("Ada").run(); // Hello, Ada
}
}Greeter exists only inside makeGreeter. The caller never sees the name. It receives a Runnable, and the concrete class stays hidden. Returning the instance through a supertype is the usual way to let a local class's behavior escape its block.
Scope rules
A local class follows the same scoping rules as a local variable.
- Declaration comes first. The name is in scope from its declaration to the end of the enclosing block. You cannot write
new Greeter()on a line above the class. - The name is invisible outside the block. Code in other methods, or after the closing brace, cannot refer to
Greeter. Two methods in the same class may each declare their own local class with the same name. - The class may refer to itself. Inside its own body, a local class can use its own name, for example to build a recursive structure.
- Later local classes may use earlier ones. A second local class in the same block can extend or instantiate the first.
flowchart TDUse the diagram below for the lifetime picture. The name is limited by the block, but instances are not.
Modifiers a local class can and cannot have
A local class is not a member of the enclosing class, so member modifiers make no sense on it.
| Modifier | Allowed on a local class? | Reason |
|---|---|---|
| `public`, `protected`, `private` | No | It is not a member, so there is no access level to set. |
| `static` | No | Whether it has an enclosing instance depends on the method it sits in. |
| `final` | Yes | It prevents subclassing, as for any class. |
| `abstract` | Yes | A later local class in the same block can extend it. |
Constructors, state, and reuse
This is where a local class differs from an anonymous class. Because it has a name, it can declare constructors and be instantiated many times.
import java.util.ArrayList;
import java.util.List;
public class Report {
static List<String> summarize(List<String> names, int limit) {
class Entry {
final String name;
final int length;
Entry(String name) {
this.name = name;
this.length = name.length();
}
boolean tooLong() { return length > limit; }
@Override
public String toString() {
return name + (tooLong() ? " (long)" : "");
}
}
List<Entry> entries = new ArrayList<>();
for (String n : names) entries.add(new Entry(n));
List<String> out = new ArrayList<>();
for (Entry e : entries) out.add(e.toString());
return out;
}
public static void main(String[] args) {
System.out.println(summarize(List.of("Ada", "Margaret", "Alan"), 5));
// [Ada, Margaret (long), Alan]
}
}Entry is a small helper type that only summarize needs. Making it a private static nested class of Report would work, but it would then be visible to the whole class, and it could not read limit directly. The local class keeps the helper next to the one method that uses it and lets it read limit.
What a local class can see
A local class can read three kinds of names from its surroundings:
- Members of the enclosing class, including private ones.
- Local variables and parameters of the enclosing method, provided they are effectively final. The next chapter covers this rule and its consequences in detail.
- Members of the local class itself and of its supertypes.
Access to the enclosing class's instance members depends on where the local class is declared. In an instance method the local class has an enclosing instance, as an inner class does. In a static method it does not.
public class Account {
private int balance = 100;
Runnable makeAudit(String label) {
class Audit implements Runnable {
@Override
public void run() {
System.out.println(label + ": " + balance);
}
}
return new Audit();
}
static Runnable makeStaticAudit() {
class Audit implements Runnable {
@Override
public void run() {
// Referring to balance here would not compile:
// a static method has no enclosing Account instance.
System.out.println("no instance");
}
}
return new Audit();
}
public static void main(String[] args) {
Account a = new Account();
Runnable live = a.makeAudit("live");
live.run(); // live: 100
a.balance = 250;
live.run(); // live: 250
makeStaticAudit().run(); // no instance
}
}The second line of output is the important one. live did not copy balance. It holds a reference to the Account object and reads the current field each time it runs. The captured local label is different. It is fixed when the Audit object is created.
The two Audit classes do not conflict. Each belongs to a different method's scope.
Local classes and the enclosing instance
In an instance method, a local class behaves like an inner class. It can use Account.this to name the enclosing object. An instance of it keeps that enclosing object reachable for as long as the local object is reachable. A later chapter on memory retention covers the consequences. For now, note that the Runnable returned by makeAudit keeps its Account alive.
In a static method, or in a static initializer, there is no enclosing instance. The local class can use only the enclosing class's static members and the effectively final locals.
Restrictions on declarations inside a local class
Before Java 16, a local class could not declare static members, except constant variables (static final fields initialized with a compile-time constant). Since Java 16, inner classes, including local classes, may declare static members. If your project targets Java 11 or 8, the older restriction still applies.
A local class cannot declare a method with the same signature as a method it must override but with weaker access. The usual override rules apply. An interface method is implicitly public, so the implementing method in a local class must be declared public. This is a common cause of compile errors when you convert an anonymous class or a lambda into a local class.
Local records, enums, and interfaces
Java 16 added local records, and later releases added local enums and interfaces. They are all implicitly static. They cannot use the enclosing method's local variables or the enclosing instance. This makes them a good fit for plain data holders.
import java.util.List;
public class LocalRecord {
public static void main(String[] args) {
record Point(int x, int y) {
int distance() { return Math.abs(x) + Math.abs(y); }
}
List<Point> points = List.of(new Point(1, -2), new Point(-3, 4));
for (Point p : points) {
System.out.println(p + " -> " + p.distance());
}
// Point[x=1, y=-2] -> 3
// Point[x=-3, y=4] -> 7
}
}This example needs Java 16 or later. Use a local record when you need a throwaway tuple, for example a grouping step in a stream pipeline. Use an ordinary local class when the type needs to read the method's variables.
Compiled form
The compiler produces a separate class file for each local class. The name starts with the enclosing class, then a $, then a number, then the local name. Greeters yields Greeters$1Greeter.class. The number distinguishes local classes with the same name in the same outer class, so the two Audit classes in Account become Account$1Audit.class and Account$2Audit.class. A later chapter covers this naming in full.
When a local class is the right choice
Choose a local class when all of these hold:
- Only one method (or one block) needs the type.
- The type needs a name, a constructor, several methods, or more than one instance.
- The type needs to read the method's parameters or locals, or the enclosing instance, without passing them through a constructor.
If the type is used in more than one method, make it a nested class. If it is a single-use implementation of one interface method, a lambda is usually shorter. If it needs a name only for readability, consider extracting a private method that returns a lambda.
Common mistakes
- Using the class before declaring it. The scope begins at the declaration, not at the start of the method.
- Forgetting
publicon an overriding method. ImplementingRunnable.runwith a package-privaterunfails to compile. - Reading an instance field from a static method. A local class in a static method has no enclosing instance.
- Assigning to a captured local. If the method changes a variable after the class uses it, that variable is no longer effectively final, and the class body no longer compiles.
Exercise
In an instance method of class Box, you declare a local class Peek that prints a private field size of Box. You return a Peek instance as a Runnable, then call box.size = 9 and run the Runnable again. Does it print the old value or the new value, and what does the answer tell you about how Peek reaches size?
Show answer
It prints the new value, 9. Peek does not copy size. In an instance method it holds a reference to the enclosing Box object and reads the field each time it runs. This is also why the returned Runnable keeps the Box reachable.
Exercise
A method has a parameter int max. Inside the method you declare a local class Check that compares values against max. Later in the same method you write max = max + 1;. What happens, and what are two ways to fix it?
Show answer
The code does not compile. max is used inside the local class, so it must be effectively final, and the later assignment breaks that. Fix it by copying the value into a new variable that is never reassigned (final int limit = max;) and using limit in Check, or by removing the reassignment and computing the new value in a separate variable.