Anonymous Inner Classes: How it works?

How it works? is our exclusive series of posts which will focus on tricky but useful concepts / features in Java SE or in its ecosystem. The purpose is to bring into light any important concepts/tricks which are immensely useful if you learn to use it properly. These tips serve as a quick refresher for learners who have already come ahead a long way in their Java journey. Today, we are starting with Anonymous Inner Classes


Because Inner Classes is such a peculiar feature, they are rarely used by beginners in day-to-day programming. Anonymous Inner Classes, on the other hand, are used all the more often and it is quite hard to get rid of them.

They are actually quite useful and also easy to use. So, let’s tackle this concept.

Prerequisites for learning Anonymous Inner Classes

  • Swing Event Delegation Model (Good to know)
  • Inner Classes (Mandatory)
  • Using Interfaces (Mandatory)

What is an Anonymous Inner Class?

By name, it is quite sufficient to understand. It is an inner class – meaning it will be coded inside another class. But call it anonymous? It it were so useful, we should give it a name. That way we will be able to create as many objects of the class as we want. Sounds simple, right? WRONG!

Quite often there will be situations where you don’t need an object of a class for more than once; it will be like “use-and-throw”. In fact, not the object, the class itself will be defined like use-and-throw. 

For example, consider an interface “Greetable” which has only one abstract method called “greetWith(String name)”. The contract of this method is to print a greeting along with the name passed to it.

To use this method, we will have to create a class which implements the “Greetable” interface and overrides the “greetWith()” method.

Using an Interface

For using an Interface, you have to create a class

 

Now, this class X can have as many objects as we want. Let’s create three of those and name them “Alpha”, “Beta”, and “Gamma”.

 

 

 

All objects will have the same implementation of greetWith() method. Since these objects will have IS-A relationship with the Greetable interface, we can see these can be referred as Greetable objects as well. All Greetable objects will have the same implementation of greetWith() method.

What if we need multiple Greetable objects, each with a different implementation of greetWith() method?

Well in that case, we will just have to create more classes. A sample is given in the image below:

Multiple Use and Throw Cases

Multiple Use and Throw Cases

 

Creating a new class and using it for only one object will lead to many “use and throw” classes. Simply speaking, to use one method, you will need three units of code.

Path from Class to Object

Path from Interface to Object

Will you really create 100 classes if you needed each of their objects only once? Talk about efficiency in design!

Anonymous Inner classes solve this problem. They are meant to be “use and throw” classes. You will not create these classes in different files and then import them to create the object. Using a special syntax, you will write the anonymous class and create the object – both at the same time.

Anonymous Inner Class

Anonymous Inner Class

 

So many websites I have seen which explain this concept either wrong or only at the syntax level. Now if anyone asks you in an interview about anonymous inner classes, you can easily explain them the need. Trust me, they will be mightily impressed with you!

Syntax of usage of Anonymous Inner Class

Watch the syntax of near object of anonymous class.

Normally, compiler won’t let you create an object of an interface. But when it sees opening curly braces instead of a semi colon after the constructor braces, it creates a temporary class in the memory which implements the interface. It then dumps the definition which comes after it into the temporary class. And once it sees the “new” keyword, it creates an object of the temporary class.

Important things to understand are:

  • The class is temporary and hence anonymous i.e. without a name.
  • The temporary class implements the interface mentioned. We are still creating object of a class which is extending the interface, except that class is not named. Therefore, we will not be able to create more objects of it.

Even though I have used the example of an interface, anonymous inner classes can be used for interfaces, abstract classes, or even any concrete class as well.

Advantages of Anonymous Inner Classes

You won’t have go to another file or location to see the class definition. This makes the code much more readable. Other developers who come after you, will thank you for using it.

Another important reason why many developers prefer using these classes is that it doesn’t pollute the package namespace with use-and-throw classes. In a large enterprise application, there will be typically hundreds of classes to maintain. Writing code is one thing, and maintaining it across many versions / releases is tricky business and needs to be done well.

Practical Example of Anonymous Inner Classes

If you have used event handling in Java, you have already used these classes before. In the event delegation model, there is a “source” object which generates an “event” object and sends it to a registered listener object. The source and listener objects are created in code, but the event object is generated at run time.

In the classic (non-scientific) calculator, each button will be the source and will generate ActionEvent object when it is clicked and will send it to a registered ActionListener object. Since ActionListener is an interface, we will need to create classes of the interface to use the callback methods defined inside it.

A single action listener will do only thing. Each button must respond differently, meaning each button will have its own unique ActionListener class & object pair. This is a classic “use-and-throw” class. Hence, anonymous inner classes are used so extensively in Java Event Handling.

Conclusion

Anonymous Inner Classes are very useful if you keep them small. Remember these are full blown classes written inside another class. The more methods you add the more difficult it is to read the code.

Leave a Reply