Anonymous Class

This concept allows us to create new instance and also declare the class at the same time. This is similar to local class but unlike local class anonymous class has no name. It is basically an expression where a class is instantiated and also declared in a single expression. The whole anonymous block is ended with a semicolon.

Anonymous Classes make code look concise as there is no need to declare a class and then create an instance of the class. Let's look at the below example, without Anonumous Class functionality we need to follow below steps to implement and instantiate an interface.

general way
interface Car {
 public void printMaker();
}
class AudCar implements Car
{
 public void printMaker(){
 System.out.println("AUDI");
}
}
Car audiCar = new AudCar();
audiCar.printMaker();

We can now achieve the same using Anonymous Class expression as below.


interface Car {
 public void printMaker();
}
Car audiCar = new Car(){
 public void printMaker(){
  System.out.println("AUDI");
 }
};//The Anonymous Class expression ends with a semicolon
audiCar.printMaker();

Click here to read about Functional Interfaces