What is the significance of an anonymous inner class?

Anonymous inner classes are a special type of inner class that allow us to create and use a class at the same time without giving it a name. They are commonly used when a class implementation is required only once, such as implementing an interface, extending a class, handling events, or creating callback logic. This helps reduce boilerplate code and keeps the implementation close to where it is used.

Key Points:

• Anonymous inner classes are declared and instantiated in a single statement. • They are useful for one-time implementations of interfaces or abstract classes. • They improve code readability by keeping small implementations close to their usage. • They cannot have constructors because they do not have a class name. • Java 8 Lambda expressions have replaced many anonymous inner class use cases for functional interfaces.

Example:

Suppose an application needs a simple Runnable implementation that will only be used once. Instead of creating a separate class file, an anonymous inner class can be used directly.

Code Example:

public class AnonymousInnerClassDemo {

    public static void main(String[] args) {

        Runnable task = new Runnable() {
            @Override
            public void run() {
                System.out.println("Task is running...");
            }
        };

        task.run();
    }
}

Interview Tip:

A concise interview answer is: "An anonymous inner class is an unnamed 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 code complexity and improve readability."