What Are Anonymous Classes?
You'll learn: What anonymous classes are and why they let you declare and instantiate a class in one expression without giving it a name.
The Core Idea
An anonymous class is a local class without a name. Instead of declaring a local class with a name (like you learned in lesson 631) and then instantiating it, you declare and instantiate it all at once, right where you need it.
Think of it like ordering a custom sandwich at a deli. With a local class, you'd write down the recipe, give it a name ("The Special"), and then order it. With an anonymous class, you just describe what you want on the spot and get it immediately—no name needed.
Why "Anonymous"?
Because the class has no identifier. You define its body inline, typically as an argument to a method or as part of an assignment. The compiler generates a name for you behind the scenes (like OuterClass$1), but you never use or see it in your code.
When You'd Use Them
Anonymous classes are most common when you need:
- A one-time implementation of an interface
- A quick subclass with minor customizations
- Short event handlers or callbacks
They combine the declaration and instantiation into a single expression, making your code more compact when the class is simple and used only once.
Key Characteristics
- No class name in your source code
- Declared and instantiated in one expression
- Can implement an interface or extend a class
- Can access effectively final local variables and enclosing class members
Key Takeaway: Anonymous classes are unnamed local classes declared and instantiated together in a single expression, perfect for simple, one-off implementations.