Anonymous Classes
TL;DR
- An Anonymous Class is an inner class declared and instantiated at the exact same time without giving it a name.
- They are used to create a one-off implementation of an Interface or abstract class.
- They were heavily used for event listeners and callbacks before Java 8 introduced Lambda expressions.
Concept
If you have an interface ClickListener, and you only need to use it in one specific button on one specific screen, creating a whole new file SubmitButtonClickListener.java is tedious.
An anonymous class lets you say: “I need an object that implements this interface right now, and I will define the method body right here.”
Because it has no name, you can never reuse it or instantiate it a second time.
Examples
interface Greeting {
void sayHello();
}
public class AnonymousDemo {
public static void main(String[] args) {
// 1. Defining and instantiating a class that implements Greeting simultaneously
Greeting englishGreeting = new Greeting() {
@Override
public void sayHello() {
System.out.println("Hello!");
}
};
// 2. Doing it again for a different implementation
Greeting spanishGreeting = new Greeting() {
@Override
public void sayHello() {
System.out.println("¡Hola!");
}
};
englishGreeting.sayHello(); // Hello!
spanishGreeting.sayHello(); // ¡Hola!
}
}
Interview Questions
Q: Can an Anonymous Class implement multiple interfaces?
A: No. An anonymous class is created using the new InterfaceName() syntax. You can only provide one interface or one class name. It is impossible to make it implement two interfaces or extend a class and implement an interface at the same time.
Q: Are Anonymous Classes obsolete because of Lambdas?
A: Mostly, yes. If the interface has exactly ONE abstract method (a Functional Interface), you should always use a Lambda expression, as it compiles to less bytecode and is vastly more readable.
However, Anonymous Classes are still required if:
- You are implementing an interface with multiple abstract methods.
- You need to declare new instance variables specific to the implementation.
- You need to use the
thiskeyword to refer to the anonymous instance itself (in a Lambda,thisalways refers to the enclosing outer class).