What are anonymous classes in Java, and what are their advantages?

Anonymous classes are classes without a declared name that are created and instantiated in a single statement. They are typically used when a class implementation is needed only once, such as implementing an interface or extending a class for a specific task.

Key Points

Example

Suppose a button click event requires a custom action. Instead of creating a separate class, an anonymous class can be used directly where the event handler is defined.

interface Greeting {

    void sayHello();
}

public class Demo {

    public static void main(String[] args) {

        Greeting greeting = new Greeting() {

            @Override
            public void sayHello() {
                System.out.println("Hello from Anonymous Class");
            }
        };

        greeting.sayHello();
    }
}

Advantages

Interview Tip

A concise interview answer is

An anonymous class is a nameless class that is declared and instantiated in a single statement. It is mainly used for one-time implementations of interfaces or abstract classes, helping reduce boilerplate code and keeping the implementation close to its point of use.

Last updated: 11 November 2026

Previous question: What methods does the Object class provide, and how are they used?

Next question: What is a singleton class in Java?

More Core Java - Level II interview questions

All Core Java - Level II questions