Java Anonymous Class


In Java, an anonymous class is a class that is defined without a name. It is a class that is used for a short-lived purpose, typically when you need to create a one-time object for a particular action. Anonymous classes enable you to instantiate and define the class in a single expression, which is useful for simplifying your code when you don’t need a named class.

In this guide, we will explore the concept of anonymous classes, their uses, syntax, examples, and how they differ from regular classes.

Table of Contents

  1. What is an Anonymous Class?
  2. Types of Anonymous Classes
  3. Syntax of Anonymous Classes
  4. Advantages of Anonymous Classes
  5. Disadvantages of Anonymous Classes
  6. Examples of Anonymous Classes
  7. When to Use Anonymous Classes

What is an Anonymous Class?

An anonymous class is a class that is defined and instantiated at the same time, without providing a class name. It is a convenient and concise way to implement classes or interfaces when you need them only once, such as when implementing event listeners or callbacks.

Anonymous classes are typically used when:

  • You want to instantiate a class only once and don't need to reuse it elsewhere.
  • You are implementing an interface or extending a class with just one method that you need to override.

Key Characteristics:

  • Anonymous classes don't have a name.
  • They are defined and instantiated in a single expression.
  • They are often used for implementing interfaces or extending abstract classes, typically for event handling or one-time tasks.

Types of Anonymous Classes

There are mainly two types of anonymous classes in Java:

2.1 Anonymous Inner Class

An anonymous inner class is an anonymous class that extends an existing class (usually abstract or a superclass) without explicitly naming the class. You define the class and instantiate it in one go, usually in the context of a method or constructor.

Example of an Anonymous Inner Class:

abstract class Animal {
    abstract void sound();
}

public class Main {
    public static void main(String[] args) {
        // Anonymous inner class extending Animal
        Animal dog = new Animal() {
            void sound() {
                System.out.println("Woof! Woof!");
            }
        };
        
        dog.sound();  // Output: Woof! Woof!
    }
}

In this example:

  • The anonymous class extends the Animal abstract class and overrides the sound() method.
  • You don't need to name the class; it is defined and used immediately.

2.2 Anonymous Class for Interfaces

An anonymous class can also be used to implement an interface without explicitly defining a class for it. This is commonly seen in event handling.

Example of an Anonymous Class Implementing an Interface:

interface Greeting {
    void greet();
}

public class Main {
    public static void main(String[] args) {
        // Anonymous class implementing the Greeting interface
        Greeting greetMorning = new Greeting() {
            public void greet() {
                System.out.println("Good Morning!");
            }
        };
        
        greetMorning.greet();  // Output: Good Morning!
    }
}

Here:

  • The anonymous class implements the Greeting interface and provides an implementation for the greet() method.

Syntax of Anonymous Classes

The syntax for an anonymous class in Java is:

ClassName referenceVariable = new ClassName() {
    // Override methods or implement abstract methods
};
  • ClassName: The class or interface you are extending or implementing.
  • referenceVariable: The variable that holds the reference to the anonymous class.
  • The method(s) to be overridden or implemented go inside the curly braces.

Example of an Anonymous Inner Class:

Runnable r = new Runnable() {
    @Override
    public void run() {
        System.out.println("Anonymous class in action!");
    }
};
new Thread(r).start();

In this case:

  • The anonymous class implements the Runnable interface and overrides the run() method.
  • It is used immediately to create a new Thread and execute the task.

Advantages of Anonymous Classes

  1. Concise Code: Anonymous classes provide a way to create and use classes in a single line, reducing the need for additional class files.
  2. Convenience: They are very useful for situations where you need to provide a one-off implementation of an interface or abstract class, such as in event listeners or threads.
  3. Increased Readability: By using anonymous classes, you avoid the clutter of defining multiple small classes, keeping your code cleaner and easier to understand.
  4. Access to Final Variables: Anonymous classes can access final local variables and parameters from the enclosing method or class, making them useful for short-lived tasks.

Disadvantages of Anonymous Classes

  1. Limited Reusability: Since anonymous classes do not have a name, they cannot be reused in different parts of your code.
  2. Can Be Hard to Debug: Anonymous classes can make the code harder to debug, as the stack trace won't contain the class name, and they might be difficult to identify.
  3. Limited Flexibility: Because the class is defined inline and cannot have a name, it may make certain patterns (like factory patterns or inheritance) harder to implement.
  4. Code Readability Issues: While concise, overuse of anonymous classes, especially in complex scenarios, can lead to code that is harder to understand and maintain.

Examples of Anonymous Classes

Here are some common use cases for anonymous classes in Java.

Example 1: Implementing an Interface with an Anonymous Class

interface Calculator {
    int add(int a, int b);
}

public class Main {
    public static void main(String[] args) {
        // Anonymous class implementing the Calculator interface
        Calculator calculator = new Calculator() {
            @Override
            public int add(int a, int b) {
                return a + b;
            }
        };
        
        System.out.println("Sum: " + calculator.add(5, 10));  // Output: Sum: 15
    }
}

Example 2: Using an Anonymous Class with an Event Listener

import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Anonymous Class Example");
        JButton button = new JButton("Click me");
        
        // Anonymous class for action listener
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                System.out.println("Button clicked!");
            }
        });
        
        frame.add(button);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}

In this example:

  • We use an anonymous class to implement the ActionListener interface for handling button click events.

When to Use Anonymous Classes

  1. For short-lived objects: When you need to implement an interface or extend a class for a one-time use, anonymous classes are perfect.
  2. Event handling: They are commonly used in GUI programming for event listeners and handling actions like button clicks, mouse events, etc.
  3. Threads and Runnables: Anonymous classes are frequently used for creating Runnable objects or extending the Thread class in multi-threaded applications.