How are anonymous inner classes used in Java?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
In Java, anonymous inner classes provide a way of creating a class instance with enhancements for a particular use without explicitly declaring a separate new subclass. They are useful when you have a small class body and need an instance only once throughout your application execution.
Understanding Anonymous Inner Classes
Anonymous inner classes are typically used in scenarios where the class definition is not likely to be reused and serves to simplify the code by keeping behavior local to where it is used. These are defined and instantiated in a single expression using the new keyword followed by the constructor of an existing class or an interface, with the class body enclosed in braces {}.
Key Characteristics
- Simplicity: They are created at the point of use, often in argument lists to method calls, especially in GUI event handling or in any situation where a handler is needed.
- No Name: As the name suggests, anonymous inner classes don’t have a name. You cannot have a constructor since the class has no name.
- Localization of Class Definition: Helps to encapsulate the class definition close to where it will be used which enhances readability.
- Brevity: Can lead to more concise code by reducing the overhead of creating a named class.
Application of Anonymous Inner Classes
Anonymous inner classes are especially prevalent in event-driven programming (like GUI applications) and situations involving callbacks. Here are a few common use cases:
- Event Handling: In frameworks like Swing, they are widely used to quickly bind event listeners directly to components.
- Runnable Implementations: When starting new threads or defining simple tasks inside methods.
- Comparator definitions: Such as in sorting, where it might not make sense to define a full comparator class elsewhere.
A Technical Example
Consider you have a graphical button in a Java Swing application that needs to print a message to the console when clicked. Instead of creating a named class that implements ActionListener, you could use an anonymous inner class directly:
In this example, the ActionListener interface is implemented by an anonymous class, providing the functionality for the actionPerformed method inline.
Comparing with Lambda Expressions
With the introduction of lambda expressions in Java 8, the usage of anonymous inner classes has been reduced in cases involving functional interfaces, which are interfaces that have only one abstract method. The former example with lambda becomes:
Lambda expressions provide a way to write even more concise and readable code in many cases where anonymous inner classes were historically used.
Advantages and Disadvantages
| Aspect | Advantage | Disadvantage |
| Readability | Encapsulates small bits of functionality where they are applied. | Can decrease readability if overused, especially with complex logic. |
| Reusability | Not designed for reuse; ideal for one-off implementations. | Poor choice for functionality that is needed in multiple places. |
| Maintainability | Localizes implementation, aiding maintenance within limited scopes. | Changes require updates at all usage points; not easily refactored. |
| Performance | On par with local classes; possibly slightly slower to instantiate. | More class definitions can slightly increase memory usage. |
Conclusion
Anonymous inner classes offer a powerful yet concise way to extend behaviors of existing classes locally within a method or in an expression. They are particularly useful in scenarios where you need a quick way to handle events or implement runnable tasks without cluttering your codebase with single-use class files. However, with advances in Java, like lambda expressions, the need for anonymous inner classes has decreased in some use cases, notably those involving single-method interfaces. Nevertheless, in complex scenarios requiring multiple method implementations, anonymous inner classes remain a valuable tool.
Related reading
- How are calls to static members of another class handled in Java Object Serialization?
- How are mvn clean package and mvn clean install different?
- How are Spring Data repositories actually implemented?
- How can a Java program get its own process ID?
- How can create a producer using Spring Cloud Kafka Stream 3.1
- How can I access a folder inside of a resource folder from inside my jar File?
- How can I access getSupportFragmentManager in a fragment?
- How can I access static class variables within methods?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.