In the non-static local class, it is not permitted to access non-final local variables from the enclosing method, but it is allowed to do so with the the non-static field inherited from the superclass. Could somebody tell me what is/are the reason(s) for this? Thank you
A class local to a method would be utilizing variables from the method. The method variables are created on the stack frame when the method is called. If the class local to the method persists (such as if it derived from a base class and overrode some methods which utilized these method local variables and this derived class is handed as a cast reference to some other class which remembers it) then when the method goes out of scope those variables point to nonexistent memory. It would be a security leak, and also cause a crash. Therefore, a local method class can not access any variables from the method itself, unless they are final (when they can be inlined)
A class can utilize variables from the superclass because it ACTUALLY IS that class- it has all the heap space the class has, including those variables. They are not going away- they are part and parcel of the derived class.
Local method variables exist during the scope of the method, and are typically destroyed when the method exits. Thus, an inner class object defined within the method has the potential to outlive those local variables. However, if these variables are final, then the compiler can copy their values into the inner class object.
As for outer-class variables... Consider that a non-static inner class can only exist in conjunction with an instance of the outer class. Therefore, variables of the outer class need not be final for a locally-defined inner class to access. (These include non-private variables inherited from a superclass, because the subclass is also an instance of the superclass.) [ September 15, 2004: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org