Anonymous class is a class without a name, used to instantate and override methods on the fly - often used for quick, one-time use.
Example
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Running anonymously");
}
};
r.run(); // "Running anonymously"
abstract class Animal {
abstract void makeSound();
}
Animal animal = new Animal() {
void makeSound() {
System.out.println("Meow");
}
};
anima.makeSound(); // "Meow"
Key Points
- Created using new keyword.
- Can extend a class or implement an interface.
- Defined inline where you need the object.
- No constructors (because the class has no name).
- Used mostly in event handling, threading or short-term behavior injection.
Real-World Analogy
Like a temporary worker - shows up, does the job and disappears. No need for a full employee profile (class definition).
Tip
If you need a one-off implementation of an interface or abstract class, think anonymous class.
Also mention that itβs less common post Java 8 due to lambdas.
Parent: _OOP Advanced Tools