Java Anonymous inner class

Java Anonymous inner class

A class that have no name is known as anonymous inner class in java. It should be used if you have to override method of class or interface. Java Anonymous inner class can be created by two ways:
  1. Class (may be abstract or concrete).
  2. Interface

Java anonymous inner class example using class

  1. abstract class Person{  
  2.   abstract void eat();  
  3. }  
  4. class TestAnonymousInner{  
  5.  public static void main(String args[]){  
  6.   Person p=new Person(){  
  7.   void eat(){System.out.println("nice fruits");}  
  8.   };  
  9.   p.eat();  
  10.  }  
  11. }  

Internal working of given code

  1. Person p=new Person(){  
  2. void eat(){System.out.println("nice fruits");}  
  3. };  
  1. A class is created but its name is decided by the compiler which extends the Person class and provides the implementation of the eat() method.
  2. An object of Anonymous class is created that is referred by p reference variable of Person type.

Internal class generated by the compiler

  1. import java.io.PrintStream;  
  2. static class TestAnonymousInner$1 extends Person  
  3. {  
  4.    TestAnonymousInner$1(){}  
  5.    void eat()  
  6.     {  
  7.         System.out.println("nice fruits");  
  8.     }  
  9. }  

Java anonymous inner class example using interface

  1. interface Eatable{  
  2.  void eat();  
  3. }  
  4. class TestAnnonymousInner1{  
  5.  public static void main(String args[]){  
  6.  Eatable e=new Eatable(){  
  7.   public void eat(){System.out.println("nice fruits");}  
  8.  };  
  9.  e.eat();  
  10.  }  
  11. }  

Output:
nice fruits

Internal working of given code

It performs two main tasks behind this code:
  1. Eatable p=new Eatable(){  
  2. void eat(){System.out.println("nice fruits");}  
  3. };  
  1. A class is created but its name is decided by the compiler which implements the Eatable interface and provides the implementation of the eat() method.
  2. An object of Anonymous class is created that is referred by p reference variable of Eatable type.

Internal class generated by the compiler

  1. import java.io.PrintStream;  
  2. static class TestAnonymousInner1$1 implements Eatable  
  3. {  
  4. TestAnonymousInner1$1(){}  
  5. void eat(){System.out.println("nice fruits");}  
  6. }  


Output:
nice fruits


Previous
Next Post »