What is an anonymous inner class?

In object -oriented computer programming, the anonymous inner class is a class that is declared inside the method but is not named. The anonymous inner class has several limitations that differ from the normal class, including the limitation of the range of variables to which it has access. There are several very specific situations in which the use of an anonymous internal class can make the source code more readable, but is primarily used to promote encapsulation where generation of separate classes could be complicated.

Engapulation is a concept in object -oriented programming (OOP) that the object and its components should be protected in some way and tied to the object. Anonymous internal classes and inner classes generally help to realize the encapsulation of particularly complex objects. Instead of having to create a class that relies on a separate outer class, it is artificially and potentially exposed to some components, an anonymous inner class can TTJ. Both together tight.

in some prograThe anonymous inner class can help overcome the limitation of a single heritage. If the object inherits from one class but then needs access to another, the inner class can be generated while running and then handed over to the relevant service doctors. This technique is common for calls and listeners of events. The only alternative would be to create a whole second class in which only one or two methods are rewritten.

Anonymous internal classes have certain limitations to prevent interruption of encapsulation and promotion. The primary limitation is that the anonymous inner class cannot access the variable method in which they reside if these variables are not declared final. This is because the inner class could continue to function after the life of the class and the method in which it nest. Variable packaging would be destroyed as soon as his life ends, so the links that hold the inner class would be the momentIt has become invalid. The only exception is the final variable because it will exist outside the instance.

One of the more specific uses for anonymous inner class is code protection. Many OOP languages ​​are provided by a mechanism called Reflection. Reflection allows the program to divide another class and find out what its membership variables and methods are, but not the code itself. By using an anonymous inner class, the inner class content is protected from reflection and the internal functioning of a larger class can be effectively hidden.

IN OTHER LANGUAGES

Was this article helpful? Thanks for the feedback Thanks for the feedback

How can we help? How can we help?