What’s an anon inner class?

Print anything with Printful



Anonymous inner classes are classes declared inside a method without a name, with restrictions on variable scope. They help achieve encapsulation and can overcome single inheritance limitations. They cannot access non-final variables and can protect code from reflection.

In object-oriented computer programming, an anonymous inner class is a class that is declared inside a method but has no name. An anonymous inner class has several restrictions that make it different from a regular class, including a restriction on the scope of variables it can access. There are some very specific situations where using an anonymous inner class can make the source code more readable, but it’s mostly used to help enforce encapsulation where generating separate classes might complicate it.

Encapsulation is the concept in object oriented programming (OOP) that an object and its components should be somehow protected and bound to the object. Anonymous inner classes, and inner classes in general, help achieve encapsulation for particularly complex objects. Instead of having to build a class that relies on a separate outer class, binding them together artificially and potentially exposing some of the components, an anonymous inner class can bind them together in a solid way.

In some programming languages, an anonymous inner class can help overcome the restrictions of single inheritance. If an object inherits from one class but then needs access to 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 a whole second class where only one or two methods are overridden.

Anonymous inner classes have some restrictions in place to prevent encapsulation breaking and to enforce scope. The main restriction is that an anonymous inner class cannot access the variables of the method in which it resides unless those variables are declared final. This is because the inner class may continue to function beyond the life of the class and method it nests within. The variables of the wrapping class would be destroyed after its life, so the references contained in the inner class would immediately become 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 ​​have 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.




Protect your devices with Threat Protection by NordVPN


Skip to content