Understanding Anonymous Inner Class in JAVA
Introduction
In Java, an anonymous inner class does not have a name and only creates a single object for that class. Anonymous inner classes can be helpful when creating objects with a few extras, such as overloading methods of classes or interfaces, without actually subclassing them.
Simply put, an anonymous inner class does not have a name. Developers should use it when they want to override a method in a class or interface. It is necessary to define anonymous classes inside other classes. Thus, it is also called an anonymous inner class.
The syntax is as follows:
class outerClass { //defining anonymous class object1 = new Type(parameterList) { // body of the anonymous class }; } |
Most of the time, anonymous classes extend subclasses or implement interfaces. There are two ways to use anonymous classes in the program.
- The anonymous class extends a superclass.
- The anonymous class that implements an interface
Anonymous Inner Classes Features
There are several essential features of an anonymous inner class in Java. Below is a list of them:
- A compiler decides the name of an anonymous inner class when it creates it since it extends a superclass or implements an interface. It cannot, however, include explicit extends or implements clauses.
- Classes must implement all the abstract methods defined in their superclasses or interfaces.
- Anonymous classes use the superclass's default constructor to create objects internally.
- The compiler names the anonymous inner class as OuterClassName$n while compiling. For example, if the program consists of the outer class named Employee with two anonymous inner classes, they are compiled as Employee$1.class and Employee$2.class.
- Anonymous inner classes can also access the members of their outer classes, just like their local inner classes.
When should you use Anonymous Inner classes in Java?
Below are a few reasons why anonymous inner classes are better than local inner classes.
1. In Java, anonymous inner classes are mainly used for instant use (i.e., one-time usage).
2. An anonymous inner class can be handy in case the class has a short body or minimum code.
3. It is helpful for classes that require only one instance.
4. In graphics programming, anonymous inner classes are helpful when creating listener interface implementation classes.
5. The best way to handle events in GUI-based applications is to use anonymous inner classes.
Code Sample
class Sample{ |
Java Anonymous Class Implementing An Interface
public class AnonymousExample { |