Java
Programming
Inner Classes
Anonymous Classes
Coding Techniques

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.

Browse interview questions

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

  1. 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.
  2. 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.
  3. Localization of Class Definition: Helps to encapsulate the class definition close to where it will be used which enhances readability.
  4. 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:

java
1JButton button = new JButton("Click Me!");
2button.addActionListener(new ActionListener() {
3    @Override
4    public void actionPerformed(ActionEvent e) {
5        System.out.println("Button was clicked!");
6    }
7});

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:

java
button.addActionListener(e -> System.out.println("Button was clicked!"));

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

AspectAdvantageDisadvantage
ReadabilityEncapsulates small bits of functionality where they are applied.Can decrease readability if overused, especially with complex logic.
ReusabilityNot designed for reuse; ideal for one-off implementations.Poor choice for functionality that is needed in multiple places.
MaintainabilityLocalizes implementation, aiding maintenance within limited scopes.Changes require updates at all usage points; not easily refactored.
PerformanceOn 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
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track 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.

Browse interview questions

All Rights Reserved.