|
Anonymous inner class is an inner class with no name. It is one of the most interesting (and weird) forms of inner classes. Its syntax may look a bit unfriendly at the beginning, but with a little practice, you will get used to it. You can create an anonymous inner class by extending any existing class. Let us consider a simple Bicycle class.
class Bicycle{
public void paddle() {
System.out.println(“paddling!”);
}
}
You can create an anonymous inner class by extending the Bicycle may look like this:
Bicycle mountainBike = new Bicycle() {
public void paddle() {
System.out.println(“paddling really hard!”);
}
};
You might feel that there is no class declaration here as there is no class keyword and class name. But believe it or not, the above code actually declares and instantiate an unnamed class. Figure 4.4 illustrates the declaration and instantiation of this anonymous class.
![]() |
Figure 4.4 Declaration and simultaneous instantiation of anonymous inner class
At the right hand side of assignment (new Bycycle() { …};), a class (without any name) is declared (within curly brackets) and instantiated.(with the new keyword). It is called as anonymous precisely because it does not have any name. The instance is then assigned to reference variable mountainBike. There are two things happening here:
An anonymous class is extending the Bicycle class and overriding its paddle() method. Even if the declaration does not have extends it is indeed extending the class Bicycle.
In the declaration of anonymous class itself, we are also creating an instance of it with new keyword. The reference to this (newly created) instance is assigned to variable mountainBike. You can call the methods of the anonymous class using this reference as:
mountainBike.paddle();
This method calls the method which the anonymous inner class is
overriding.
Therefore “Paddling really
hard!” is printed.
|
|
Remember that variable mountainBike is of type Bicycle. But still when you call method mountainBike.paddle(),“paddling really hard!” is printed. Java does dynamic linking for methods (see chapter 11). It means that the method to be invoked at runtime is decided based on the actual object that is being referred by the reference variable at runtime and not by the type of that variable. In our example, though the variable mountainBike is of type Bicycle, it is actually referring to the anonymous class’s instance. Hence mountainBike.paddle() will invoke the paddle() method of the anonymous class. |
There is a reason why an instance of anonymous class must be created at the same time of its declaration. To create an instance we have to have a class name, but anonymous class does not have a name. So we cannot create an instance later as there won’t be any class-name to refer to. Therefore, the instance is created right where the class is declared. Hence, the declaration and creation of anonymous class is always done at the same time.
|
|
Anonymous class always has only one instance. |