Why we should use only final local variables from inner classes?
hey . I don't know why inner classes only can access final local variables? Could you help me?
Re: Why we should use only final local variables from inner classes?
Hi, ramclever!
After a little digging, I found this post.
So here's what's going on:
Inner classes behave a little bit differently than variables. Whereas the variables in a method are "cleaned" (removed from the stack, never to be seen again) after the method in which they are contained completes its run, inner classes can, in some cases, remain even after the method has finished, due to the fact that the inner classes are sometimes passed as arguments to other methods that can delay the use of the classes.
As you may see, this could result in a very large problem: an inner class could request the value of a local variable after it has been deleted from the stack! This would not be good at all, so to ensure that the correct value can be used in the inner class, the compiler requires that the local variable(s) in question be final. Marking these variables as final allows Java to, at runtime, create a copy of the variable that can safely passed to the inner class.
Re: Why we should use only final local variables from inner classes?
Quote:
Originally Posted by
ramclever
hey . I don't know why inner classes only can access final local variables? Could you help me?
for variable protection purpose.for the particular variable used only in that same class.