Local internal class references local variables in the external class must be final attributes!

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.