stock market

What Are Anonymous Classes in Java and When to Use Them?

An anonymous class in Java is a class without a name that is both defined and instantiated in a single expression. Developers commonly use anonymous classes to create instances of classes or implement interfaces without writing a separate named class. This helps in writing cleaner and more concise code, especially for short-term or one-time use cases in Java programming.

Characteristics of Anonymous classes

Anonymous class is

  • A local class without a name
  • Define and initiated at the same time
  • often used to provide short term implementations of interface or abstract class
  • Mainly used in event handling thread creation or callback mechanism

Example: Example without Anonymous class

1. Greeting.java (Interface)

2. GreetingImpl.java (Interface Implementation)

3. DemoTest.java

Amazon
-68% ₹829

Women's Maroon Poly Crepe A-Line Kurta Set With Dupatta

  • Kurta Material: Poly Crepe || Pant Material: Poly Crepe || Dupatta Material: Georgette
  • Style: Straight kurta || Calf Lenth with 3/4 Sleeve
  • This Product Ready Chest Size: Small= 36 (Inch) || Medium=38 (Inch) || Large=40 (Inch) || Xl=42 (Inch) || XXl=44 (Inch)


We earn a commission if you make a purchase, at no additional cost to you.

Example: Example with Anonymous class

  • Defines an interface named Greeting
  • It has one method sayHello() , which does not return anything and does not take any parameters .
  • Start of class definition named main
  • It contains the main() method , which is the entry point of any java application
  • main() method where the program starts running
  • String[] args allows command line argument to be passed to the program
  • We are creating an object of an anonymous class that implements the greeting interfaces .
  • new Greeting() start the instantiation and the {..} block defines the body of the anonymous class.
  • This class does have a name and is used only once
  • Implementation of the sayHello() method from the Greeting interface , it prints a message to the console when called .
  • closes the anonymous class definition

1. Greeting.java (Greeting Interface)

2. DemoTest.java

Leave a Reply

Your email address will not be published. Required fields are marked *

RkdigitalSchool