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 a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.