As shown in the example, a partial internal class timerprint is declared. The method in this class references a local variable testtxt, which must be declared as final !!Why?
Logically:This internal class appears inside a method, but during actual compilation, the internal class is compiled into outer $ 1timerprint. Class. This shows that the external class and the internal class areAt the same level. In other words, the twoDifferent lifecycles! After the start is called, non-final variables will disappear, and the internal class reference will be invalid! HoweverScope(The scope of this internal class is in this method ).
Practice: Java compilerIs like this (The precondition is that the variable is referenced in the internal class.):
If it is defined as final, the Java compiler will generate an external variable in the internal class timerprintCopyAnd can ensure the internal classCan be referencedExternal attribute, which can guarantee the valueUniqueness.
If it is not defined as finalCompilation failed! (Jdk1.6 tested ). Because the compiler does not copy non-final variablesThe variables referenced by the internal class are invalid!
Bytecode after external class Compilation:
Bytecode after internal class Compilation:
If the variable d in the external class is not referenced by the internal class, final is optional andThe Java compiler will not handle this specially !!
Compiled external class:
Compiled internal class:
References: http://blog.csdn.net/whuslei/article/details/6251020