top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Anonymous Class in Java

Introduction

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.

Overview

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.

Syntax of Anonymous Class in Java

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:

  • We start by declaring a variable of the superclass type and assigning it to a new superclass instance.

  • We then use the open curly braces {} to define the body of the anonymous inner class.

  • Inside the anonymous inner class body, we can provide implementations for methods or add additional members as needed. These implementations and members are specific to the anonymous inner class and do not affect the superclass or other classes.

Java Anonymous Inner Class Example Using Class

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.

Internal Class Generated By The Compiler

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.

Java Anonymous Inner Class Example Using Interface

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.

Internal Class Generated By The Compiler   

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.

Types of Anonymous Inner Class   

Anonymous inner classes in Java can be classified into two types:

  • Anonymous inner classes that extend a class: These classes are created and instantiated simultaneously without explicitly defining a separate class. They can override methods and access variables of the superclass. Such classes are useful for event handling and providing custom implementations for abstract classes.

  • Anonymous inner classes that implement an interface: Similar to the previous type, these classes are defined and instantiated inline without explicitly creating a separate class. They provide implementations for methods defined in the interface. These classes are commonly used for situations requiring one-time implementations, such as listeners or callbacks.

Example: Anonymous Class Extending a Class

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.

Example: Anonymous Class Implementing an Interface

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. 

Advantages of Anonymous Classes

Anonymous classes in Java provide several advantages:

  • Conciseness and Inline Definition: Anonymous classes allow you to define and instantiate a class in a single step without needing a separate class declaration. This makes the code shorter and eliminates the need for additional class files.

  • Localized Implementation: Anonymous classes are commonly used for small, specific tasks or one-time implementations. They encapsulate the implementation within the relevant context, making the code more focused and easier to understand.

  • Improved Readability: By defining a class inline where it is used, anonymous classes make the code more straightforward and comprehensible. The implementation is directly associated with its usage, enhancing code clarity.

  • Access to Local Variables: Anonymous classes can access local variables from the enclosing method or block in which they are defined. This allows for convenient usage of a local state within the anonymous class.

  • Customization and Flexibility: Anonymous classes can override methods and provide custom implementations for abstract classes or interfaces. This enables on-the-fly behavior customization, providing flexibility to adapt to specific needs.

  • Event Handling: Anonymous classes are frequently used for event handling in graphical user interfaces. They offer a convenient way to define and handle events concisely without needing separate event listener classes.

Conclusion

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.

FAQs

  1. How to use anonymous class in Java?

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.

  1. How anonymous class implements interface Java?

Anonymous classes can implement interfaces in Java by providing the necessary implementation for the interface methods within the body of the anonymous class declaration.

  1. What is lambda, and how is it different from anonymous class?

Lambda expressions are a concise way to represent anonymous functions, offering a more streamlined syntax than anonymous classes for functional programming tasks.

Leave a Reply

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