Anonymous Classes

There are two special kinds of inner classes:

  1. local classes
  2. anonymous classes.

Why is it called an anonymous inner class?

The reason it’s called an anonymous inner class is because the class that we have created clearly has no name.

How to create an anonymous inner class ?

Anonymous classes in java are defined in a different way than that of a normal java classes. In java anonymous classes can be created in either of the two ways.

  1. Using a class reference variable.
  2. Using an interface.

1) Using a class reference variable.

import java.lang.*;
class  Interest
{    			 
	 double calculate(double amt,double rate,double time)
	 {
	   double  i=(amt*rate*time)/100;
	   return(i);
	 }
}

public class soft 
{
	
public  static void main(String  args[])
{
	// Here is Anonymous class  
	Interest i= new Interest()
	{
		 @Override  
		 double calculate(double amt,double rate,double time)
		 {
			  double  i=(amt* Math.pow( (1+(rate/100)), time)) -amt;
			   return(i);
		 }
	};
	  double r= i.calculate(1000,5, 2);
	  System.out.println("Compound Interest::"+r);
	  Interest  q= new Interest();
	   r= q.calculate(1000,5, 2);
	   System.out.println("Simple Interest::"+r);
	
	}

}

output
Compound Interest::102.5
Simple Interest::100.0

Explanation:

In above piece of code; see the code line Interest i= new Interest() {, there is a brace at the end of line, not a semicolon.This curly brace opens the class definition and declares a new class that has no name (anonymous class).Now let's enter into the body of newly defined subclass of class Interest and you will see that calculate() is being overridden. This is the crux of defining an anonymous inner class because we want to override one or more methods of the super class on the fly.

2) Using an interface.

import java.lang.*;
interface  Interest
{
    			 
	double calculate(double amt,double rate,double time);
	
}
public class soft 
{
	
public  static void main(String  args[])
{
	// Here is Anonymous class  
	Interest i= new Interest()
	{
		@Override
		public  double calculate(double amt,double rate,double time)
		 {
			  double  i=(amt* Math.pow( (1+(rate/100)), time)) -amt;
			   return(i);
		 }
	};		
	 double r= i.calculate(1000,5, 2);
	 System.out.println("Compound Interest::"+r);
  }

}

output
Compound Interest::102.5