An Anonymous Inner Class is a nested class without a name and for which only a single object is created. Think of it as a "Quick Fix" or a "Disposable Class." Use it when you need to override a method of a class or an interface just once, without creating a separate .java file.
In standard Java, to use an interface, you must:
1. Create a class
2. Implement the interface
3. Instantiate the class.
An Anonymous Class combines all these steps into one single expression.
new keyword.You can create an anonymous class in three specific scenarios:
When you want to override methods of a concrete class on the fly.
When you need to provide an implementation for an abstract class without making a subclass.
The most common use: providing logic for an interface's methods instantly.
The syntax looks a bit strange at first because the class definition ends with a semicolon (;). This is because it is considered a single Java statement.
InterfaceName obj = new InterfaceName() {
// Method implementation
};
If you have ever done GUI programming (Swing or Android), you've used Anonymous Inner Classes for button clicks. Instead of creating a ButtonClickHandler class, you just write the logic right where the button is defined.
Runnable interface is a standard industry practice for quick, background tasks.
Watch how we implement the Greet interface without actually creating a named class like "EnglishGreeting" or "HindiGreeting."
In modern Java (Version 8 and above), Anonymous Inner Classes are often replaced by **Lambdas**. However, they are NOT the same.
| Feature | Anonymous Inner Class | Lambda Expression |
|---|---|---|
| Type | A class (even if it has no name). | A functional representation. |
| Scope of 'this' | Refers to the Anonymous class itself. | Refers to the enclosing class. |
| Capabilities | Can implement multiple methods. | Can only implement one method. |
.class file (e.g., Outer$1.class), which can slightly increase the memory footprint if overused.Q: Can an anonymous class be static?
A: No. By definition, they are inside a method or a block, so they cannot be declared as static.
Q: Why do we need the semicolon at the end?
A: Because an anonymous class is defined as part of an expression (assignment), and all Java expressions must end with a semicolon.
Q: Can an anonymous class access local variables?
A: Yes, but only if the variable is final or effectively final (meaning its value doesn't change after initialization).
Anonymous Inner Classes are the Swiss Army knife of Java. They are perfect for small, localized tasks where creating a full class would be overkill. While Lambdas have taken over much of their territory, understanding Anonymous classes is essential for reading legacy code and handling complex multi-method interfaces.
Next: Master Java Abstraction →