«Back to Home

Core Java

Topics

Anonymous Inner Class In Java

Anonymous inner class

The classes which have no name are called as Anonymous inner class in Java. It must be used, if we have to override the method of class or the interface.
 
In other words, if we declare any inner class without a class name, it is called as an Anonymous inner class. We can declare and instantiate them at the same time. Usually these classes are used, when we need to override the method of a class or an interface in Java.
 
Syntax

AnonymousInner an_inner = new AnonymousInner(){
         public void my_method(){
      }
};
 
Anonymous inner class can be created by two types, which are,
  • Class

  • Interface
Let’s see an example, using class, given below.
 
Code
  1. abstract class Tiger {  
  2.     abstract void eat();  
  3. }  
  4. public class Cub {  
  5.     public static void main(String args[]) {  
  6.         Tiger t = new Tiger() {  
  7.             void eat() {  
  8.                 System.out.println("eat nonveg");  
  9.             }  
  10.         };  
  11.         t.eat();  
  12.     }  
  13. }  
4

Output

5
 
Internal working of this program is given below.

6
 
In the example, mentioned above, a class is created but its name is decided by the compiler, which extends the Tiger class and provides the implementation of eat () method. An object of Anonymous class is created, which is referred by t reference variable of Tiger type.
 
Let’s see an example, using interface, given below.
 
Code
  1. interface Runable {  
  2.     void run();  
  3. }  
  4. public class Cub {  
  5.     public static void main(String args[]) {  
  6.         Runable r = new Runable() {  
  7.             public void run() {  
  8.                 System.out.println("Run fast");  
  9.             }  
  10.         };  
  11.         r.run();  
  12.     }  
  13. }  
7

Output

8

Internal working of this program

It performs two important tasks.

9
 
In the example, mentioned above, a class is created but its name is decided by the compiler, which implements the Runable interface and provides the implementation of the run() method and an object of Anonymous class is created, which is referred by r reference variable of Runable type.
 
Summary

Thus, we learnt that the classes, which have no name are called as Anonymous inner class in Java and also learnt how it works internally.