Tutorial Playlist
The anonymous class in Java is a way to create an unnamed class that extends a superclass or implements an interface on the fly. They are often used for one-time implementations or event handlers. Anonymous classes are defined and instantiated in a single step, providing a concise and inline approach for certain scenarios. Learn more about anonymous classes in this tutorial.
In this tutorial, we'll explore how to use anonymous class in Java with examples. You will also learn how to extend a superclass or implement an interface, providing a concise and inline approach for certain programming scenarios.
Here is the syntax for using the anonymous class in Java:
SuperClass obj = new SuperClass() {
  // Anonymous inner class body
  // Implementations of methods or additional members
};
Let us break down the syntax:
public class upGradTutorials {
  public static void main(String[] args) {
    // Creating an instance of the class using anonymous inner class
    MyClass myClass = new MyClass() {
      @Override
      public void displayMessage() {
        System.out.println("Hello, I'm an anonymous inner class!");
      }
    };
    // Calling the method on the anonymous inner class object
    myClass.displayMessage();
  }
}
// Class to be extended by anonymous inner class
class MyClass {
  public void displayMessage() {
    System.out.println("Hello, I'm the base class!");
  }
}
This example has a base class MyClass with a method displayMessage(). We create an instance of this class using an anonymous inner class. The anonymous inner class is defined and instantiated inline without explicitly declaring a separate class.
We override the displayMessage() method inside the anonymous inner class and provide our custom implementation. When we call the displayMessage() method on the anonymous inner class object, it executes the overridden method, printing "Hello, I'm an anonymous inner class!" to the console.
When we compile the Java code containing an anonymous inner class, the compiler generates a separate class file for the anonymous inner class. The generated class file has a name that combines the outer class's name, a dollar symbol ($), and a number. The number represents the order of appearance of the anonymous inner class in the code.
For example, if we compile the above code, the compiler will generate a class file named upGradTutorial$1.class for the anonymous inner class.
public class upGradTutorials {
  public static void main(String[] args) {
    // Creating an instance of the interface using an anonymous inner class
    MyInterface obj = new MyInterface() {
      @Override
      public void doSomething() {
        System.out.println("Anonymous inner class implementation of doSomething method");
      }
    };
    Â
    // Calling the method using the interface reference
    obj.doSomething();
  }
}
// Interface definition
interface MyInterface {
  void doSomething();
}
Inside the main method, we create an instance of an anonymous inner class that implements the MyInterface interface. The anonymous inner class is defined using the new MyInterface() { ... } syntax.
We implement the doSomething() method within the anonymous inner class, which simply prints the message "Anonymous inner class implementation of doSomething method".
After creating the anonymous inner class instance, we assign it to a variable obj of type MyInterface. This allows us to reference the object and call methods defined in the interface.
Finally, we invoke the doSomething() method on the obj object, which calls the overridden doSomething() method within the anonymous inner class and prints the desired message to the console.
The Java compiler generates a class for the anonymous inner class behind the scenes, with a name similar to upGradTutorials$1. This internal class contains the implementation of the interface method. However, as a developer, we do not need to explicitly create this class, as the compiler automatically generates it.
The generated class is a subtype of the interface or superclass that the anonymous inner class implements or extends. In this case, the compiler generates a class file that implements the MyInterface interface.
The generated class has a synthetic name, meaning it is not explicitly named in the source code. It allows us to create an interface instance without explicitly defining a separate class that implements the interface. The anonymous inner class simplifies the code by providing a concise way to implement interfaces or extend classes on-the-fly without the need for a separate named class implementation.
Anonymous inner classes in Java can be classified into two types:
public class upGradTutorials {
  public static void main(String[] args) {
    // Creating an instance of the abstract class using an anonymous inner class
    AbstractClass obj = new AbstractClass() {
      @Override
      public void display() {
        System.out.println("Anonymous inner class implementation of display method");
      }
      @Override
      public void additionalMethod() {
        System.out.println("Additional method implementation in the anonymous inner class");
      }
    };
    // Calling methods using the abstract class reference
    obj.display();
    obj.additionalMethod();
  }
}
// Abstract class definition
abstract class AbstractClass {
  public abstract void display();
  public void additionalMethod() {
    System.out.println("Default implementation of additionalMethod");
  }
}
In this example, we define an anonymous inner class that extends the AbstractClass abstract class. The anonymous inner class provides implementations for the abstract display() method and another method, additionalMethod().
Inside the main method, we create an instance of the AbstractClass using the syntax new AbstractClass() { ... }. Within the anonymous inner class, we override the display() method and provide a custom implementation that prints a specific message. We also override the additionalMethod() and provide a custom implementation.
After creating the anonymous inner class instance, we assign it to a variable obj of type AbstractClass. This allows us to reference the object and call the overridden methods.
Finally, we invoke the display() and additionalMethod() methods on the obj object. Since the anonymous inner class extends the AbstractClass, the overridden implementations within the anonymous inner class are executed, printing the custom messages to the console.
public class upGradTutorials {
  public static void main(String[] args) {
    // Creating an instance of the interface using an anonymous inner class
    MyInterface obj = new MyInterface() {
      @Override
      public void printMessage(String message) {
        System.out.println("Anonymous inner class implementation: " + message);
      }
      @Override
      public void additionalMethod() {
        System.out.println("Additional method implementation in the anonymous inner class");
      }
    };
    // Calling methods using the interface reference
    obj.printMessage("Hello, World!");
    obj.additionalMethod();
  }
}
// Interface definition
interface MyInterface {
  void printMessage(String message);
  void additionalMethod();
}
This example defines an anonymous inner class that implements the MyInterface interface. The anonymous inner class provides implementations for the printMessage() method and another method, additionalMethod().
Inside the main method, we create an instance of the MyInterface using the syntax new MyInterface() { ... }. Within the anonymous inner class, we override the printMessage() method and provide a custom implementation that prints the message with additional text. We also override the additionalMethod() and provide a custom implementation.
After creating the anonymous inner class instance, we assign it to a variable obj of type MyInterface. This allows us to reference the object and call the overridden methods.
Finally, we invoke the printMessage() and additionalMethod() methods on the obj object. Since the anonymous inner class implements the MyInterface, the overridden implementations within the anonymous inner class are executed, printing the custom messages to the console.
Anonymous classes in Java provide several advantages:
Anonymous class in Java provides a powerful and convenient way to define and instantiate classes inline without separating class declarations. They offer advantages such as conciseness, localized implementations, improved code readability, access to local variables, customization, and flexibility.
Anonymous classes are beneficial for one-time implementations, event handling, and providing custom implementations for abstract classes or interfaces. You can write more concise, focused, and readable code in Java by leveraging anonymous classes. Sign up for a professional course at upGrad to hone your skills in various Java concepts.
Anonymous classes are defined and instantiated inline without a specific class name. Anonymous classes in Java are declared and instantiated simultaneously, allowing you to create a one-time-use class without explicitly defining it.
Anonymous classes can implement interfaces in Java by providing the necessary implementation for the interface methods within the body of the anonymous class declaration.
Lambda expressions are a concise way to represent anonymous functions, offering a more streamlined syntax than anonymous classes for functional programming tasks.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...