Anonymous Inner Class in Java
An anonymous it is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overriding methods of a class or interface, without having to actually subclass a class.
Anonymous inner classes are useful when a class needs to be created and used only once. They are particularly useful for providing implementations of interfaces or abstract classes. They allow for the creation of an object with a single defined behavior without the need to create a separate class.
Code Snippet
//Anonymous Inner Class in Java
abstract class testDemo {
abstract void display();
}
class outerDemo {
public void outerDisplay() {
testDemo o = new testDemo() {
@Override
public void display() {
System.out.println("Test Display");
}
};
o.display();
}
}
public class App {
public static void main(String[] args) {
outerDemo o = new outerDemo();
o.outerDisplay();
}
}