Anonymous classes in Java
If we need to create one object only for a inner class which extends or implements another class, we can define the class directly in the statement or expression where you need to create the object without the separate class definition. This is called as anonymous class.
The class is defined and instantiated at the same time without any class name (only with name of interface to be implemented or name of the class to be extended).
General Syntax
new Name(){ }
Name - name of the class which is to extended or name of the interface
Example 1
class License{
public void license_id(){
System.out.println("License number is 123354");
}
}
class People{
public static void main(String args[]){
License person1=new License(){
public void license_id(){
System.out.println("License number is 544456");
}
};
person1.license_id();
}
}
Output
License number is 544456
Example 2
class Mobile{
interface Sim{
public void customer_care();
}
public static void main(String args[]){
Sim vodafone=new Sim(){
public void customer_care(){
System.out.println("Customer care number is 121");
}
};
vodafone.customer_care();
}
}
Output
Customer care number is 121
Anonymous class only applicable for the class that needs to extend or implement another class. These type of classes are used largely in UI or graphical applications.