Anonymous Inner Class

//Anonymous Inner Class
  1. Over View

  2. Anonymous inner class that extends a class.

  3. Anonymous inner class that implements an interface.

  4. Anonymous inner class that defined as arguments of method / constructor.

  5. General Classes vs Anonymous Inner Classes

1. Anonymous Inner Class :

Sometimes we can declare inner class without name such type of inner classes are called anonymous inner classes.

The main objective of anonymous inner classes is “just for instant use”.
There are 3 types of anonymous inner classes

  1. Anonymous inner class that extends a class.
  2. Anonymous inner class that implements an interface.
  3. Anonymous inner class that defined as arguments of method / constructor.

2. Anonymous inner class that extends a class :

Below is the example for Anonymous inner class that extends a class.
And you can declare the following in anonymous classes:
1. Fields
2. Extra methods (even if they do not implement any methods of the super type)
3. Instance initializers
4. Local classes
5. However, you cannot declare constructors in an anonymous class.

Inside Anonymous inner classes we can take or declare new methods but outside of anonymous inner classes we can’t call these methods directly because we are depending on parent reference.

Example 1 :

Example 2 :

3. Anonymous inner class that implements an interface :

Example :

4. Anonymous inner class as argument of method / constructor :

Example :

5. General Class vs Anonymous Inner Class :

 

General  Classes Anonymous Inner Classes
1. A general class can extends only one class at a time. 1. Anonymous inner class also can extends only one class at a time.
2. A general class can implement any no. Of interfaces at a time. 2. Anonymous inner class can implement only one interface at a time.
3. A general class can extends a class and can implement an interface    simultaneously. 3. anonymous inner class can extends a class or can implements an interface but not both simultaneously.
4. In normal Java class we can write constructor because we know name of the class. 4. Anonymous inner class we can’t write constructor because anonymous inner class not having any name.