An anonymous inner class is an inner class which is declared without any class name at all. In other words, a nameless inner class is called an anonymous inner class. Since it does not have a name, it cannot have a constructor because we know that a constructor name is the same as the class name.
We can define an anonymous inner class and create its object using the new operator at the same time in one step.
Syntax
new(argument-list){ // Anonymous class body }
Types of Anonymous Inner Class in Java
- Anonymous inner class that extends a class
- Anonymous inner class that implements an interface
- Anonymous inner class as an argument
Anonymous inner class that extends a class
Here a new keyword is used to create an object of the anonymous inner class that has a reference of parent class type.
Example
class Car { public void engineType() { System.out.println("Turbo Engine"); } } public class AnonymousClassDemo { public static void main(String args[]) { Car c1 = new Car(); c1.engineType(); Car c2 = new Car() { @Override public void engineType() { System.out.println("V2 Engine"); } }; c2.engineType(); } }
Output
Turbo Engine V2 Engine
Anonymous inner class that implements an interface
Here a new keyword is used to create an object of the anonymous inner class that has a reference of an interface type.
Example
interface Software { public void develop(); } public class AnonymousClassDemo1 { public static void main(String args[]) { Software s = new Software() { @Override public void develop() { System.out.println("Software Developed in Java"); } }; s.develop(); System.out.println(s.getClass().getName()); } }
Output
Software Developed in Java AnonymousClassDemo1$1
Anonymous inner class as an argument
We can use the anonymous inner class as an argument so that it can be passed to methods or constructors.
Example
abstract class Engine { public abstract void engineType(); } class Vehicle { public void transport(Engine e) { e.engineType(); } } public class AnonymousInnerClassDemo2 { public static void main(String args[]) { Vehicle v = new Vehicle(); v.transport(new Engine() { @Override public void engineType() { System.out.println("Turbo Engine"); } }); } }
Output
Turbo Engine