Home » Java Anonymous Inner Class

Java Anonymous Inner Class

by Online Tutorials Library

Java Anonymous inner class

Java anonymous inner class is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overloading methods of a class or interface, without having to actually subclass a class.

In simple words, a class that has no name is known as an anonymous inner class in Java. It should be used if you have to override a method of class or interface. Java Anonymous inner class can be created in two ways:

  1. Class (may be abstract or concrete).
  2. Interface

Java anonymous inner class example using class

TestAnonymousInner.java

Test it Now

Output:

nice fruits  

Internal working of given code

  1. A class is created, but its name is decided by the compiler, which extends the Person class and provides the implementation of the eat() method.
  2. An object of the Anonymous class is created that is referred to by ‘p,’ a reference variable of Person type.

Internal class generated by the compiler

Java anonymous inner class example using interface

Test it Now

Output:

nice fruits  

Internal working of given code

It performs two main tasks behind this code:

  1. A class is created, but its name is decided by the compiler, which implements the Eatable interface and provides the implementation of the eat() method.
  2. An object of the Anonymous class is created that is referred to by ‘p’, a reference variable of the Eatable type.

Internal class generated by the compiler


Next TopicLocal Inner class

You may also like