Java Local and Anonymous Classes (OCP 21)
Local and anonymous classes for the OCP 21 exam: classes inside methods, capturing effectively final locals, outer-instance access, anonymous subclasses and implementations, the trailing semicolon, local records, lambdas versus anonymous classes, and choosing a nested type.
kvi5hnuCode Sprout team member9 min readOn this page
The previous article covered nested classes declared at member level. This one covers the two kinds declared inside code: a local class, which has a name and lives inside a method or block, and an anonymous class, which has no name and is declared and instantiated in one new expression.
Both share one central rule. They can use local variables of the enclosing method only if those variables are final or effectively final.
Local classes
A local class is declared inside a method, constructor or initializer block. Like a local variable, it exists only from its declaration to the end of that block:
public class Gym {
private int capacity = 40;
void plan() {
final int rooms = 3;
class Schedule { // local class
int perRoom() { return capacity / rooms; }
}
System.out.println(new Schedule().perRoom()); // 13
}
}
Its properties:
- No access modifier and no
static. Writingprivate class Scheduleorstatic class Scheduleinside a method doesn't compile ("illegal start of expression"). - It may be
finalorabstract, and it may extend a class and implement interfaces. - It can declare fields, methods, constructors and, since Java 16, static members.
- It can be used only after its declaration.
new Schedule()above the declaration gives "cannot find symbol". - Declared in an instance method, it has a hidden reference to the outer object, so it can read and write all outer members, including
privateones. Declared in a static method, there's no outer object, and touching an instance field gives "non-static variable … cannot be referenced from a static context". - It compiles to its own class file with a number in the name, such as
Gym$1Schedule.class.
Final and effectively final locals
A local class may read the enclosing method's local variables and parameters only if they're final or effectively final, meaning they're never assigned again after initialization. The test is easy to apply: if you could add final to the declaration without causing an error, the variable is effectively final.
void paint() {
final int coats = 2;
int width = 10;
int height = 4;
class Wall {
int litres() { return coats * width * height; } // DOES NOT COMPILE
}
width = 12; // this reassignment makes width not effectively final
}
The error is "local variables referenced from an inner class must be final or effectively final". It points at the use of width inside Wall, even though the reassignment comes later in the method. coats is fine (it's final), and height is fine (never reassigned).
Why the rule? A local-class object can outlive the method call, for example when the method returns it. Java handles this by copying the captured values into the object when it's created. If the variable could change later, the copy and the original would disagree, so the language forbids changing it at all.
Outer fields are different. They aren't copied, they're reached through the outer object, so they can change freely.

Local records, enums and interfaces
Since Java 16 you can also declare records, enums and interfaces inside a method. They're implicitly static, so they can use neither the enclosing method's locals nor the outer object's instance members:
public class Survey {
int answers = 12;
void run() {
int weight = 2;
record Vote(int value) {
int scaled() { return value * weight; } // DOES NOT COMPILE
int all() { return answers; } // DOES NOT COMPILE
}
}
}
Both errors say "non-static variable … cannot be referenced from a static context". A local record is a good fit for grouping intermediate values inside one method, as long as it gets everything through its components.
Anonymous classes
An anonymous class is a local class without a name. It's declared and instantiated in one expression, new Type(args) { body }, where Type is either:
- a class, which the anonymous class extends, passing
argsto that class's constructor, or - an interface, which it implements. Then the parentheses must be empty, or you get "anonymous class implements interface; cannot have arguments".
It must extend exactly one class or implement exactly one interface, never both and never two interfaces.
public class Cafe {
abstract static class Deal {
abstract int discount();
}
int price(int base) {
Deal happyHour = new Deal() {
int discount() { return 2; }
}; // the semicolon ends the statement
return base - happyHour.discount();
}
}
The ; after the closing brace is required whenever the anonymous class is part of an assignment or another statement, because the whole thing is one expression. Leaving it out gives "';' expected".
Rules to know
- Interface methods are
public. An anonymous class implementing an interface must declare its methodspublic, or you get "attempting to assign weaker access privileges". - No constructor. An anonymous class has no name, so it can't declare a constructor. Writing
Deal() { }inside one is read as a method without a return type and fails. Use an instance initializer block{ ... }instead. - Constructor arguments go to the superclass.
new Greeting("hola") { ... }calls theGreeting(String)constructor. - No modifiers. You can't write
public,abstract,finalorstaticon an anonymous class. It's never abstract, so it must implement every abstract method it inherits. - Can't extend a
finalclass or a sealed type.new F() { }for afinal Fgives "cannot inherit from final". Sealed types reject it with "anonymous classes must not extend sealed classes". - Same capture rule as local classes: only final or effectively final locals.
- Extra methods are invisible through the variable's type. If you declare
int bonus()in an anonymousDeal, thenhappyHour.bonus()doesn't compile, becausehappyHouris aDeal. Withvar, the variable gets the anonymous type, and the extra method becomes callable.
var counter = new Object() {
int next() { return 7; }
};
System.out.println(counter.next()); // 7: var keeps the anonymous type
Where anonymous classes appear
They're allowed anywhere an expression is allowed:
public class Climber {
interface Grip { String hold(); }
private final Grip crimp = new Grip() { // field initializer
public String hold() { return "crimp"; }
};
static int count(int[] xs, java.util.function.IntPredicate test) {
int c = 0;
for (int x : xs) if (test.test(x)) c++;
return c;
}
public static void main(String[] args) {
int n = count(new int[] {3, 8, 12}, new java.util.function.IntPredicate() { // method argument
public boolean test(int v) { return v > 5; }
});
System.out.println(n); // 2
}
}
Anonymous classes compile to numbered class files: Climber$1.class, Climber$2.class and so on, in source order.
Anonymous classes versus lambdas
When the target is a functional interface (an interface with exactly one abstract method, chapter 8), a lambda does the same job with far less code:
Comparator<String> byLength = new Comparator<String>() {
public int compare(String a, String b) { return a.length() - b.length(); }
};
Comparator<String> byLength2 = (a, b) -> a.length() - b.length();
They are not interchangeable in every case:
| Anonymous class | Lambda | |
|---|---|---|
| Target | any class (even abstract) or any interface | functional interface only |
| Several methods, fields, state | yes | no |
this means | the anonymous object | the enclosing object |
| May redeclare an enclosing local's name | yes (it's a new scope) | no ("already defined") |
| Captures locals | final / effectively final | final / effectively final |
| Generated class file | yes (Outer$1.class) | no (the class is created at run time) |
Both capture by the same rule. The difference in this is a common exam trick: inside an anonymous class, this.toString() calls the anonymous object's method, while inside a lambda it calls the enclosing object's method. To reach the outer object from an anonymous class, write Outer.this.
Choosing a nested type
| You need… | Use |
|---|---|
| a helper tied to each outer object, used in several methods | inner class |
| a helper that doesn't need outer state | static nested class (or nested record/enum) |
| a named helper used in one method only | local class or local record |
| a one-off implementation with state or several methods | anonymous class |
| a one-off implementation of a functional interface | lambda |
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Since Java 16, local records, enums and interfaces are allowed, and they're implicitly static. Lambdas (article 46) replaced most anonymous classes that implement a single-method interface.
Exam traps from this article
A complete example
The program keeps a team's scores. It uses an anonymous class as a field initializer, a local class that reads both the outer object and a captured local, a local record for totals, an anonymous subclass of an abstract class, and an anonymous Comparator next to its lambda equivalent.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Solution {
interface Rule {
boolean accepts(int score);
}
abstract static class Badge {
private final String label;
Badge(String label) { this.label = label; }
abstract boolean earned(int score);
String label() { return label; }
}
private final String team;
private final List<Integer> scores = new ArrayList<>();
Solution(String team) { this.team = team; }
// Anonymous class as a field initializer
private final Rule positive = new Rule() {
@Override
public boolean accepts(int score) { return score > 0; }
};
void record(int... values) {
for (int v : values) if (positive.accepts(v)) scores.add(v);
}
List<String> report(int threshold) {
int bonus = 5; // effectively final: captured below
// Local class: sees the outer instance (team, scores) and the captured locals
class Line {
private final int score;
Line(int score) { this.score = score; }
String text() {
String mark = score + bonus >= threshold ? "pass" : "miss";
return team + ": " + score + " + " + bonus + " -> " + mark;
}
}
// Local record: implicitly static, so it may NOT use bonus, threshold or team
record Totals(int count, int sum) {
double average() { return count == 0 ? 0 : (double) sum / count; }
}
List<String> out = new ArrayList<>();
int sum = 0;
for (int s : scores) {
out.add(new Line(s).text());
sum += s;
}
Totals t = new Totals(scores.size(), sum);
out.add("count=" + t.count() + " average=" + t.average());
return out;
}
public static void main(String[] args) {
Solution club = new Solution("Hawks");
club.record(12, -3, 7, 18);
club.report(15).forEach(System.out::println);
// Anonymous subclass of an abstract class, with a constructor argument
Badge gold = new Badge("gold") {
@Override
boolean earned(int score) { return score >= 18; }
};
System.out.println(gold.label() + " earned by 18? " + gold.earned(18));
// Anonymous class passed directly as an argument, then the lambda equivalent
List<String> names = new ArrayList<>(List.of("kiwi", "fig", "banana"));
names.sort(new Comparator<String>() {
@Override
public int compare(String a, String b) { return a.length() - b.length(); }
});
System.out.println("anonymous comparator: " + names);
names.sort((a, b) -> b.length() - a.length());
System.out.println("lambda comparator: " + names);
// Generated class names
System.out.println(club.positive.getClass().getName() + ", " + gold.getClass().getName());
}
}
Output:
Hawks: 12 + 5 -> pass
Hawks: 7 + 5 -> miss
Hawks: 18 + 5 -> pass
count=3 average=12.333333333333334
gold earned by 18? true
anonymous comparator: [fig, kiwi, banana]
lambda comparator: [banana, kiwi, fig]
Solution$1, Solution$2
Points to notice:
positiveis an anonymousRulestored in a field, and it filters out-3.Linereadsteamthrough the hidden outer reference and copiesbonusandthreshold, which are effectively final.Totalsis a local record. It's implicitly static, so all its data comes in through its components.new Badge("gold") { ... }passes"gold"to the abstract class's constructor and supplies the missing method.- The anonymous classes are named
Solution$1,Solution$2, … in source order. The local classes compile toSolution$1LineandSolution$1Totals.
Common questions
Can a local class be used outside its method? Not by name. But an instance can escape, for example when the method returns it typed as an interface or superclass. The captured values travel with it, which is exactly why they must not change.
Is "effectively final" the same as final?
For capturing purposes, yes. The only difference is that you didn't write the keyword. Adding final to an effectively final variable never changes behavior.
Should I still write anonymous classes? Use a lambda for functional interfaces. Anonymous classes remain useful for abstract classes, interfaces with several methods, and one-off objects that need their own fields.
Summary
- Local classes are declared inside a method or block, take no access modifier or
static, and may befinalorabstract. - Local and anonymous classes may use enclosing locals and parameters only if they're final or effectively final. In instance contexts, they can also use all outer members.
- Local records, enums and interfaces are implicitly static and can't capture anything.
- An anonymous class extends one class or implements one interface, has no constructor or modifiers, and needs a trailing
;in a statement. - Lambdas replace anonymous classes for functional interfaces, but
thismeans the enclosing object in a lambda.
Practice quiz
Test yourself with the local and anonymous classes quiz: 10 exam-style questions with explanations.
Previous: Java Nested Classes: Inner Classes and Static Nested Classes (OCP 21)
Next: Java Polymorphism: Reference Types, Casting and Virtual Method Calls (OCP 21)
Related reading
- Java Nested Classes: Inner Classes and Static Nested Classes (OCP 21)
- Java Sealed Classes and Interfaces: sealed, permits, final and non-sealed (OCP 21)
- Java Interfaces: Declaring, Implementing and Inheriting Abstract Methods (OCP 21)
- Java Abstract Classes and Abstract Methods (OCP 21)
- Java Inheritance and Class Modifiers: extends, Object, this and super (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.