Anonymous Classes in Java (Part 10)


 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:-
 class Machine {  
      public void start() {  
           System.out.println("Parent Machine Starting.");  
      }  
 }  
 public class MyClass {  
      public static void main(String args[]) {  
           Machine mac = new Machine() {  
                public void start() {  
                     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:
 static class Machine$1 extends Machine {  
      Machine$1() {                 
      }  
      public void start() {  
       System.out.println("Child Machine Starting.");  
   }  
 }  



2. By Interfaces


Eg:-
 interface Animal {  
      void sleep();  
 }  
 public class MyClass {  
      public static void main(String args[]) {  
           Animal dog = new Animal() {  
                public void sleep() {  
                     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:
 static class Animal$1 extends Animal {  
      Animal$1() {                 
      }  
      public void sleep() {  
       System.out.println("Dog sleeping.");  
   }  
 }


< Previous Next >