As you say, we cannot access local variables from within a local inner class, but here is a trick you can use:
Now the trickInt array reference is final (1), but you can change the value of it's contents (2).
I think the reason why local variables (from the primitive type) have to be final, has to do with object lifetime. From within the method in which the local class is created, you could pass its (object) reference outside. Then you would run into problems when the inner class tries to access variables that do not exist after the method has finished. [ October 19, 2004: Message edited by: Zoots Allures ]
The final keyword behaves differently when applied to primitives and object references. With a primitive, final makes the value a constant, however with an object reference, final makes the reference a constant. This also applies to arrays. So once the reference is initialised, it cant be changed to point to another object or array, however the object or array can be modified. [ October 19, 2004: Message edited by: Nigel Browne ]
Joined: Aug 05, 2002
Guys, I undoorsdtood the concept of fonal object ref. But my point is how JVM treats final local variable? It must be different then the non-final local variables.
Originally posted by Alpesh Parekh: Because the local variables aren’t guaranteed to be alive as long as the method-local inner class object, the inner class object can’t use them. Unless the local variables are marked final!
But how come local varibles which are final are allowed to access?
What happens is that the compiler creates a field in the inner class and copies the value of the local variable to it. This is save because the value of the variable can't change. If the variable were not final, you could get quite confusing results - changing the value of the local variable not being reflected inside the inner class, that is.
Does that help?
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus