Short answer. It is defined in the specification as such.
Longer answer. Technically neither should work. The scope of the class (even method local class), is not the same as the scope for local variables. It is possible to store objects (or return objects) of the method local class, and hence, it is possible for the local variable to be out of scope when the object needs them.
Now... in the specification, final variables are allowed. The reason is, since final variables do not change, and it is possible for the compiler to detect whether it has been initialized, that if so... it is allowed, because the inner class can make a copy of the variable.
Inner classes in Scala make so much more sense. I don't know if you have to make variables final like this, but private members are actually private in Scala. So you can't access an inner class' private members from the outer class like you can in Java.
Henry Wong wrote:
The reason is, since final variables do not change, and it is possible for the compiler to detect whether it has been initialized, that if so... it is allowed, because the inner class can make a copy of the variable.
Henry I like your answer in that both should be disallowed, final or not.
But I don't understand your second part. Even if the variable was not declared final the inner class could still make a copy, no?
Thanks guys for this explanation. Since now I've thought that the final modifier somehow changes the place where the variable lives.
It's because first I've read (K. Sierra & B. Bates) that all local variables lives on the stack. That's why the method inner class cannot use these variables, as they might not exist anymore (the method could finished) while the object is still alive.
Then I've read that it's possible to access final local variables / parameters and asked myself: why? Does the final modifier changes the place in which the variable resides - from stack to heap or what?
Thanks for clearing this up - maybe someone in the future who will be preparing for SCJP will have this cleared up :-)