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: • Anonymous classes allow creating and using a class in one place without defining a separate class file. • They are commonly used for one-time implementations of interfaces or abstract classes. • They help reduce boilerplate code and keep related logic close to where it is used. • Anonymous classes can access final or effectively final variables from the enclosing scope. • Since Java 8, lambda expressions are often preferred for functional interfaces, but anonymous classes are still useful when multiple methods need to be implemented.
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.
Code Example:
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: • Less code compared to creating a separate class • Better readability for one-time implementations • Keeps implementation localized • Useful for event handling and callback logic • Avoids creating unnecessary class files
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."