Anonymous Classes in Java (Part 10)
Pre-requisites:- Inner Classes , Interface , Method Overridding
Anonymous Classes
It is an inner class without a name and for objects cannot be 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 create a subclass for it.
Anonymous inner classes are useful in writing implementation classes for listener interfaces in graphical user interface programming (GUI) .
Syntax:-
Class_name[obj name]= new Class_name() {//anonymous class (child class) //override methods of parent classes / interfaces / abstract classes};
Declaring an Anonymous Classes
An Anonymous class in Java can be created by two ways:
1. By Classes (Abstract or Normal)
Eg:-
classMachine{ public voidstart() { System.out.println("Parent Machine Starting."); } } public classMyClass{ public static void main(String args[]) { Machinemac= new Machine() { public voidstart() { System.out.println("Child Machine Starting."); } };mac.start(); } }
Output:-
Child Machine Starting. Working Of Compiler:
- A class is created but its name is decided by the compiler which extends the Machine class i.e child of Machine Class and provides the override of the start( ) method.
- An object of Anonymous class is created that is referred by mac reference variable of Machine type.
Internal Class generated by compiler:
staticclassMachine$1 extends Machine{Machine$1() { } public voidstart() { System.out.println("Child Machine Starting."); } }
2. By Interfaces
Eg:-
interfaceAnimal{ voidsleep(); } public classMyClass{ public static void main(String args[]) { Animaldog= new Animal() { public voidsleep() { System.out.println("Dog sleeping."); } };dog.sleep(); } }
Output:-
Dog sleeping.
Working of compiler:-
- A class is created but its name is decided by the compiler which implements the Animal interface and provides the override of the sleep( ) method.
- An object of Anonymous class is created that is referred by animal reference variable of Animal type.
Internal Class generated by compiler:
staticclass Animal$1 extends Animal{Animal$1() { } public voidsleep() { System.out.println("Dog sleeping."); } }

