Implementing Interfaces with Anonymous Classes
What you'll learn: How to create inline implementations of interfaces using anonymous classes without writing separate class files.
The Core Idea
Anonymous classes let you implement an interface right where you need it, without declaring a separate named class. Instead of creating a full class file that implements an interface, you write the implementation inline—perfect for one-time-use objects or simple callback patterns.
Think of it like ordering a custom sandwich at a deli. Rather than creating a permanent menu item (a named class), you specify exactly what you want on the spot (anonymous class). You get your sandwich once, use it immediately, and move on.
The Syntax Pattern
When implementing an interface with an anonymous class, you use this structure:
InterfaceName variable = new InterfaceName() {
// implement required methods here
};
Notice the unusual syntax: you appear to be "instantiating" an interface (which normally isn't allowed), but you're actually creating an anonymous class that implements that interface.
A Practical Example
interface Greeting {
void sayHello(String name);
}
public class Demo {
public static void main(String[] args) {
Greeting greeting = new Greeting() {
@Override
public void sayHello(String name) {
System.out.println("Hello, " + name + "!");
}
};
greeting.sayHello("Alice"); // prints: Hello, Alice!
}
}
Here, instead of creating a separate class that implements Greeting, we define the implementation inline. The anonymous class exists only at this location and has no reusable name.
Key Takeaway: Anonymous classes let you implement interfaces inline without creating separate class files—ideal for simple, one-off implementations where declaring a full class would be overkill.