Sub topic 8
Anonymous classes
This chapter assumes you know how to write classes, interfaces, abstract classes and method overriding. It also assumes you know the difference between instance and static members, and that you have seen Runnable and Comparator. It builds on the earlier chapters on local classes and variable capture.
What an anonymous class is
An anonymous class is a class with no name. You declare it and create one instance of it in a single expression. It is the right tool when you need a one-off subclass or interface implementation and a named class would add noise.
The syntax is a new expression followed by a class body:
new TypeName(constructorArguments) {
// fields, methods, initializer blocks
}TypeName is either an interface or a class. It is never the name of the new class, because the new class has none. The whole expression has a value, so you can assign it, pass it as an argument, or return it.
public class Hello {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello from an anonymous class");
}
};
r.run();
}
}The compiler creates a class that implements Runnable, then creates one instance of it. The trailing semicolon ends the assignment statement, not the class body.
Interface or class as the supertype
An anonymous class always has exactly one direct supertype, and it can come in two forms.
- Interface. The anonymous class implements the interface, and its superclass is
Object. You cannot pass constructor arguments, because interfaces have no constructors. The parentheses stay empty. - Class. The anonymous class extends that class, abstract or concrete. Whatever you put in the parentheses is passed to the matching superclass constructor.
An anonymous class cannot implement several interfaces, and it cannot extend a class and also implement an interface. The implements and extends clauses do not exist in this syntax. If you need more than one supertype, use a named class.
You also cannot extend a final class this way, for the same reason you cannot extend it normally.
Constructor arguments and initializer blocks
Because the class has no name, it cannot declare a constructor. Constructors are named after their class. Two features cover the usual needs.
- Arguments in the parentheses go to the superclass constructor.
- An instance initializer block, a bare
{ ... }in the body, runs after the superclass constructor finishes. Field initializers run in the same phase, in source order.
public class Args {
static abstract class Shape {
protected final String name;
Shape(String name) { this.name = name; }
abstract double area();
@Override
public String toString() { return name + " area=" + area(); }
}
public static void main(String[] args) {
double side = 3;
Shape sq = new Shape("square") {
{
System.out.println("initializer runs after Shape(String)");
}
@Override
double area() { return side * side; }
};
System.out.println(sq);
}
}The output is:
initializer runs after Shape(String)
square area=9.0The string "square" reaches Shape(String). The method area() reads the local variable side from the enclosing method, which is allowed because side is effectively final.
State and extra members
An anonymous class body can declare fields and methods, not only overrides. The fields give the instance its own state.
public class AnonymousState {
static abstract class Task {
abstract void run();
}
public static void main(String[] args) {
Task t = new Task() {
private int calls;
@Override
void run() {
calls++;
System.out.println("calls = " + calls);
}
};
t.run(); // calls = 1
t.run(); // calls = 2
}
}There is a catch. The variable t has the static type Task, so code outside the anonymous body cannot see calls or any new method you added. Only the members declared by the supertype are reachable through t. The exception is var. With var t = new Object() { int x = 5; };, the inferred type is the anonymous class itself, so t.x compiles. This is occasionally useful for a local, throwaway record-like value.
Capturing variables
An anonymous class can use local variables and parameters from the enclosing method, with the same rule as local classes: each one must be final or effectively final. The compiler copies the value into a hidden field of the anonymous instance. That is why the variable cannot change afterwards. The copy and the original would disagree.
public class Capture {
public static void main(String[] args) {
int total = 0;
Runnable r = new Runnable() {
@Override
public void run() {
// total++; // compile error: total is not effectively final
System.out.println("total is " + total);
}
};
r.run();
}
}Uncommenting total++ fails to compile. In fact, the line total++ would make the variable not effectively final, so even the println would be rejected. When you need a mutable counter, either keep it as a field of the anonymous class, as in the previous section, or use a holder such as AtomicInteger or a one-element array. Prefer a field when the state belongs to the object.
The meaning of `this`
Inside an anonymous class, this refers to the anonymous instance, not to the enclosing object. To reach the enclosing instance, write Outer.this, which only works in a non-static context.
public class ThisDemo {
private final String label = "outer";
Runnable make() {
return new Runnable() {
private final String label = "anon";
@Override
public void run() {
System.out.println(label); // anon
System.out.println(this.label); // anon
System.out.println(ThisDemo.this.label); // outer
}
};
}
public static void main(String[] args) {
new ThisDemo().make().run();
}
}The field label in the anonymous body shadows the outer field, so the plain name label finds the nearer declaration first. This is the same shadowing rule as for member inner classes.
An anonymous class created in a static method has no enclosing instance. It cannot use Outer.this and cannot touch the outer class's instance members. It can still use static members and effectively final locals.
Restrictions
The compiler enforces these limits on anonymous classes.
| Restriction | Reason |
|---|---|
| No explicit constructors | The class has no name to give a constructor. |
| Cannot be `abstract`, `static`, or `final` by modifier | Modifiers cannot be written in the syntax. The class is implicitly never abstract and is not static. |
| One direct supertype only | No `extends` or `implements` clause. |
| Cannot be instantiated again | There is no name to write after `new`. You get exactly one instance per evaluation of the expression. |
| Must implement every abstract method | An anonymous class can never remain abstract. |
Static members are also limited in older Java versions. Before Java 16, an anonymous class could declare static fields only if they were compile-time constants (static final with a constant value). From Java 16 onward, inner classes, including anonymous ones, may declare static members.
Compiled form and runtime identity
Each anonymous class gets its own class file. The compiler names it after the top-level or enclosing class, a dollar sign, and a number that counts anonymous classes in that enclosing class.
public class Names {
public static void main(String[] args) {
Object o = new Object() { };
Runnable r = new Runnable() {
@Override
public void run() { }
};
System.out.println(o.getClass().getName()); // Names$1
System.out.println(r.getClass().getName()); // Names$2
System.out.println(o.getClass().getSimpleName().isEmpty()); // true
System.out.println(o.getClass().isAnonymousClass()); // true
}
}Compilation produces Names.class, Names$1.class and Names$2.class. Numbers follow source order within the enclosing class, so inserting a new anonymous class earlier in the file renumbers the later ones. This matters for serialization of anonymous instances and for tools that match class names. Avoid depending on the numbers. getSimpleName() returns an empty string, which surprises logging code that uses it.
Anonymous classes versus lambdas
When the supertype is an interface with exactly one abstract method, a lambda can often replace the anonymous class.
import java.util.Arrays;
import java.util.Comparator;
public class SortDemo {
public static void main(String[] args) {
String[] words = {"pear", "fig", "banana"};
Comparator<String> anonymous = new Comparator<String>() {
@Override
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
};
Comparator<String> lambda =
(a, b) -> Integer.compare(a.length(), b.length());
Arrays.sort(words, anonymous);
System.out.println(Arrays.toString(words)); // [fig, pear, banana]
Arrays.sort(words, lambda);
System.out.println(Arrays.toString(words)); // [fig, pear, banana]
}
}Both comparators behave the same here, but they differ in several ways.
this. In a lambda,thisis the enclosing object. In an anonymous class, it is the anonymous instance.- Scope. A lambda body is not a new scope, so a lambda parameter or local cannot reuse the name of an enclosing local variable. An anonymous class body is a new scope, and its fields and method parameters may shadow enclosing names.
- State. A lambda has no fields of its own.
- Targets. A lambda targets only functional interfaces. It cannot extend a class, and it cannot implement an interface with two or more abstract methods.
- Class files. A lambda does not produce a separate class file at compile time. The JVM generates its implementation at runtime.
Common mistakes
- Double-brace initialization. Code such as
new ArrayList<String>() {{ add("a"); }}creates an anonymous subclass ofArrayListon every evaluation, with a hidden outer reference. It adds a class file and can breakequalscomparisons that checkgetClass(). UseList.of(...)or normaladdcalls. - Long anonymous bodies. When the body grows past a dozen lines, a named class or a private nested class is easier to read and test.
- Forgetting
@Override. A typo in a method name silently adds a new method, and the compiler then reports that the abstract method is unimplemented, which obscures the real cause. - Assuming access from outside. Extra members are invisible through the supertype reference, as shown earlier.
Exercise
A method contains int count = 0; followed by an anonymous Runnable whose run() does count++. Why does this not compile, and what are two ways to fix it?
Show answer
An anonymous class captures a copy of each local variable it uses, so the variable must be final or effectively final. Incrementing count inside the class (and the fact that the variable changes at all) breaks that rule. Fix 1: declare a field in the anonymous class body, such as private int count;, and increment that. Fix 2: keep the state in a mutable holder such as AtomicInteger count = new AtomicInteger(); and call count.incrementAndGet(), because the variable reference itself never changes.
Exercise
In an instance method of class Box, an anonymous Runnable declares no fields. Inside its run(), what does this refer to, and how do you refer to the Box object that created it?
Show answer
this refers to the anonymous Runnable instance. Use Box.this to reach the enclosing Box object.