What is a local inner class? Why are the salient features of it? What are the constraints imposed on such a class ? Explain the same with proper syntax
A class, which is defined in a method, is known as local inner class.The scope of such a
class is only within the method block in which it is defined. Just like a local variable. Local inner classes have the following salient features:
• Like standard classes, local classes can also have instances of their own and can
access any members, including private members, of the class in which they belong.
• Local classes can also access any local variables, methods that are in the scope of
the local method definition and are declared final.
Local inner classes have the following constraint:
• The name of a local class is defined only within the method block in which they belong.
It can never be used outside that block. However, instances of a local class created
within the scope of the class can continue to exist outside of that scope.
• Local inner classes cannot be declared public, protected, private, or static. These
modifiers are for members of classes; they are not allowed with local variable
declarations or local class declarations.
• Local inner classes cannot contain static fields, methods, or classes. Only constants in an
inner class can be declared as static and final.
• As said earlier, a local class can use the local variables, method parameters, and even exception parameters that are in its scope but only if those variables or parameters are declared final. This is because the lifetime of an instance of a local class can be much longer than the execution of the method in which the class is defined . For this reason, a local class must have a private internal copy of all local variables it uses (these copies are automatically generated by the compiler). The only way to ensure that the local variable and the private copy are always the same is to insist that the local variable is final.
No comments :
Post a Comment