Anonymous Inner class
=====================================
Some time we can declare inner class without name, such types of inner classes are called Anonymous inner class.
The main purpose of Anonymous inner classes is just for instant use (One time use).
Type of Anonymous inner class
Based on declaration and behavior there are 3 types of anonymous inner class
- Anonymous inner class that extends a class.
- Anonymous inner class that implements a interface.
- Anonymous inner class that define inside argument.
Anonymous inner class that extends a class
The generated class files are:
Analysis
PopCorn p1 = new PopCorn(){
public void test()
{
System.out.println("Spicy");
}
};
- We are declaring a class that extends PopCorn without name( anonymous inner class).
- In that child class we are overriding test method.
- For that child class we are creating an object with parent reference.
- PopCorn p1 = new PopCorn();
- Just we are creating PopCorn objec
Defining a thread by extending Thread class
Anonymous inner class that implements an Interface
Anonymous inner class that define inside Argument
(Extended version of previous Runnable anonymous class)
Normal Java class VS Anonymous inner class
- A normal java class can extends only one class at a time, of-course anonymous inner class also extends only one class at a time.
- A normal java class can implements any number of interfaces simultaneously but anonymous inner class can implements only one interface at a time.
- A normal java class can extends a class and can implements any number of interface simultaneously.
- But anonymous inner class can extends a class or can implements a interface but not both simultaneously.
- In normal java class we can write any number of constructors.
- But in anonymous inner class we can't write any constructors. (because the name of the class and constructor must be same, but anonymous inner class not having nay name.)
Note:
- If the requirement is standard and required several time then we should go for normal top level class.
- If the requirement is temporary and required only once (instant use) then we should go for anonymous inner class.
Where anonymous inner class is best suitable
We can use anonymous inner classes frequently in GUI based application to implements event handling.