What Is an Anonymous Inner Class?
In object-oriented computer programming, an anonymous inner class is a class that is declared inside of a method but is unnamed. An anonymous inner class has several restrictions that make it different from a normal class, including a restriction on the scope of the variables it can access. There are some very specific situations in which using an anonymous inner class can make source code more readable, but it is primarily used to help enforce encapsulation where the generation of separate classes could complicate it.
Encapsulation is the concept in object-oriented programming (OOP) that an object and its components should be in some way protected and bound to the object. Anonymous inner classes, and inner classes in general, help to realize encapsulation for particularly complex objects. Instead of having to create a class that relies on a separate external one, binding them together artificially and potentially exposing some of the components, an anonymous inner class can tie the two together solidly.
In some programming languages, an anonymous inner class can help to overcome the restrictions of single inheritance. If an object inherits from one class but then needs to access another, an inner class can be generated on the fly and then passed to the appropriate handlers. This technique is common with callbacks and event listeners. The only alternative would be to create an entire second class in which only one or two methods are overridden.
Anonymous inner classes have some restrictions in place to prevent breaking encapsulation and to enforce scope. The primary restriction is that an anonymous inner class cannot access variables of the method in which it resides unless those variables are declared as final. This is because the inner class could continue functioning beyond the life of the class and method in which it nests. The variables of the wrapping class would be destroyed once its life was over, so the references the inner class held would become instantly invalid. The only exception to this is a final variable, because it will exist beyond the instance.
One of the more specific uses for an anonymous inner class is code protection. Many OOP languages provide for a mechanism called reflection. Reflection allows a program to dissect another class and see what its member variables and methods are, but not the code itself. By using an anonymous inner class, the contents of the inner class are protected from reflection and the inner workings of the larger class can be effectively hidden.
Discuss this Article
Post your comments