The method local inner classes can only access the final variables of the method enclosing.
Why is it so? what is the special treatment to final variables?
Ans:
You see, the access that inner classes have to local (method) variables and parameters is an illusion. You don't have any access to local variables. What happens behind the scenes is that the Java compiler creates instance variables in your inner class which contain copies of the local variables you "access".
The problem is, if either the method or the inner class were allowed to change its copy of the variable, the different copies would get out of sync and the illusion would be shattered. This is why the compiler forces you to declare the variable final: so that it can freely generate multiple copies and create the illusion that your inner class has access to them.
The inner class implementation is full of such trickery. It had to be, because Sun added them to the Java language without changing the JVM spec. For example, the special access that inner (and nested) classes have to private variables of their enclosing class is... you guessed it... an illusion. Access is granted through special accessor methods generated by the compiler.
If you don't believe me, use javap to disassemble some class files that have inner classes
0 Comments:
Post a Comment
<< Home