Anonymous Inner Class in Java
intermediate· OOP · Nested Classes
Problem
An anonymous inner class is a one-off implementation of an interface or class, written and instantiated in a single expression, with no class name of its own.
Implement a Notifier interface inline, right where a single instance of it is needed, without declaring a separate named class.
Input
notifier.notify("Effective Java")
Output
Notification: "Effective Java" is now available
Java Program
Java
interface Notifier {
void notify(String bookTitle);
}
public class AnonymousInnerClassDemo {
public static void main(String[] args) {
// Implements Notifier inline — no separate named class is declared
Notifier notifier = new Notifier() {
@Override
public void notify(String bookTitle) {
System.out.println("Notification: \"" + bookTitle + "\" is now available");
}
};
notifier.notify("Effective Java");
}
}Output
Notification: "Effective Java" is now available
Core Logic
Writing the interface's implementation directly inside the `new Notifier() { ... }` expression skips the step of declaring a separate named class just to create a single instance.
How It Works
- 1
interface Notifierdeclares one method,notify(String), with no implementation. - 2
new Notifier() { ... }creates an instance of an unnamed class that implementsNotifierright at the point of use. - 3The body between the braces supplies
notify()'s implementation, the same as a named class would, just without ever being given a name. - 4
notifier.notify("Effective Java")calls that implementation like any other interface method call.
Calling
notifier.notify("Effective Java") runs the body written inline, printing "Notification: \"Effective Java\" is now available".💡
Key Point: This only makes sense for a single, throwaway instance — needing the same implementation in more than one place is a sign a named class (or a lambda, for a single-method interface) would serve better.
Key Concepts
anonymous classinterface implementationone-off instance