Sub topic 8
Anonymous Classes
This chapter assumes you can write Java classes, implement interfaces, extend abstract classes, and override methods. It also assumes you understand the difference between an instance member and a static member.
An anonymous class is a class declared and instantiated in one expression. It has no class name, so you use it when you need a small, one-time implementation.
Basic syntax
The expression begins with new, followed by either an interface or a class name. The class body then overrides methods or adds members.
public class Reminder {
public static void main(String[] args) {
Runnable task = new Runnable() {
@Override
public void run() {
System.out.println("Meeting starts soon");
}
};
task.run();
}
}Runnable is an interface with one method, run. The anonymous class supplies that method. The resulting object is stored in a variable whose type is Runnable.
An anonymous class can implement one interface or extend one class. It cannot extend a class and implement additional interfaces in the same declaration.
Extending an abstract class
An anonymous class can extend an abstract class. This is useful when the implementation is short and will not be reused elsewhere.
public class AnonymousState {
static abstract class Task {
abstract void run();
}
public static void main(String[] args) {
Task task = new Task() {
private int calls;
@Override
void run() {
calls++;
System.out.println("calls = " + calls);
}
};
task.run();
task.run();
}
}The output is:
calls = 1
calls = 2The anonymous class has its own calls field. Each call changes the same object. A lambda cannot replace this example directly because a lambda can target only a functional interface, not an abstract class, and the lambda itself cannot declare ordinary instance fields.
An anonymous class may contain fields, methods, initializer blocks, and overridden methods. It cannot declare a named constructor because it has no class name. Constructor arguments after the superclass or interface parentheses are passed to the superclass constructor.
class Label {
private final String text;
Label(String text) {
this.text = text;
}
void print() {
System.out.println(text);
}
}
public class LabelDemo {
public static void main(String[] args) {
Label label = new Label("Important") {
@Override
void print() {
System.out.println("[" + text() + "]");
}
private String text() {
return "Important";
}
};
label.print();
}
}Scope and `this`
Inside an anonymous class, this refers to the anonymous object. If the anonymous class is inside an outer object, use OuterClass.this to refer to that enclosing object.
Anonymous classes can also read local variables and parameters from the surrounding method. Such variables must be final or effectively final, meaning their values are assigned once and never changed.
When to choose one
Choose an anonymous class when:
- The implementation is used only once.
- The type is an abstract class rather than a functional interface.
- The object needs private fields or helper methods.
- You need explicit class scope and an object-specific
this.
Use a named class when the implementation is reused, large, or important enough to deserve its own API. Use a lambda when a functional interface is sufficient and the shorter syntax remains clear.
Exercise
Why can the Task example use an anonymous class but not a lambda directly?
Show answer
Task is an abstract class, not a functional interface, and the implementation needs its own calls field.