Sometimes you need a one-off implementation of an interface and don't want to create a named class for it. An anonymous class lets you implement an interface (or extend a class) inline, right where you need it.
Drawable d = new Drawable() {
public void draw() {
System.out.println("Drawing inline");
}
public double area() {
return 0;
}
};
The syntax looks unusual: new Drawable() followed by a class body in braces. You're not instantiating the interface directly. You're creating an unnamed class that implements Drawable and immediately making one instance of it.
Anonymous classes are common in event handlers and callbacks. In modern Java, lambdas replace them in many cases, but you'll still see anonymous classes when an interface has more than method.