What’s meant by anonymous class in Java?

In Java programming, an intriguing concept known as an anonymous class emerges, offering a unique approach to class declaration and instantiation. Unlike regular classes that possess a defined name, an anonymous class is created and instantiated in a single statement without being explicitly assigned a name.

Anonymous classes find wide application within the Java platform, serving as a compelling alternative to lambda expressions commonly employed in functional programming languages. When there is a need to create a class that will be instantiated only once, anonymous classes provide a concise and convenient solution.

It's important to note that an anonymous class must fulfill the requirement of implementing an interface or extending an abstract class. However, the familiar "extends" or "implements" keywords are not utilized when defining an anonymous class. Instead, a specific syntax is employed to declare and instantiate it, exemplifying the unique nature of this construct.

new interface-or-class-name() { class-body }
Example
public Hello hello = new Hello() { public void sayHello() { System.out.println("Hello ...."); } };

Anonymous classes can be useful in a variety of situations. For example, they can be used to:

  1. Implement an interface that only needs to be used once.
  2. Extend a class that only needs to be used once.
  3. Provide a specific implementation of a method or constructor.
  4. Anonymous classes can be a bit confusing at first, but they can be a powerful tool when used correctly.

Here are some of the differences between anonymous classes and normal classes in Java:

  1. Anonymous classes do not have a name.
  2. Anonymous classes are created and used in the same place.
  3. Anonymous classes can only be used once.
  4. Anonymous classes can only extend a class or implement an interface.