Java Anonymous inner class


An inner class that has no class name which is called an anonymous inner class. It is generally used whether you need to override the method of a class or an interface.

Syntax:

 AnonymousInner ai = new AnonymousInner(){
   public void Method_Name() {
      ........
      ........
   }   
};

Example

To override the method of a class using anonymous inner class.

 abstract class Calculate{  
	abstract void Result(); 
    int a=5,b=6,c; 
}  
public class AnonymousInnerClass{  
	public static void main(String args[]){  
		Calculate ca=new Calculate() {  
			void Result(){
			    c=a+b;
            	System.out.println("The result is "+c);
            }  
		};  
  ca.Result();  
 }  
}

Example

The anonymous inner class using interface.

interface Calculate{  
	void Result(); 
}  
public class AnonymousInnerClassinterface{  
	public static void main(String args[]){  
		Calculate ca=new Calculate() {  
			public void Result(){
            	System.out.println("The anonymous inner class using interface");
            }  
		};  
  ca.Result();  
 }  
} 



Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.