Hi I was going through the SCJP book about the innerclasses, and found this statement, it goes something like this.
A method local class can only refer to the local variables which are marked
final
and in the explanation the reason specified is about the scope and lifetime of the local class object and the local variables on the heap, but I am unable to understand that. Am I missing anything here about final??
The reason is, when the method local class instance is created, all the method local variables it refers to are actually copied into it by the compiler. That is why only
finalvariables can be accessed. Afinalvariable or reference is immutable, so it stays in sync with its copy within the method local object. Were it not so, the original value / reference could be changed after the creation of the method local class, giving way to confusing behaviour and subtle bugs.Consider this example from the JavaSpecialist newsletter no. 25:
The compiler turns the inner class into this: