One note: The external variables referenced by the inner class must be final

Source: Internet
Author: User

Previously wrote a project, long time no update, recently turned up the previous code, found here reported a mistake. (now go to IntelliJ, once in Eclipse Luna can be compiled, Eclipse Mars will also error, JDK version is 1.8, not to check why)

Why is it necessary to declare an external variable in an inner class as final?

At first I was thinking about the memory model of Java. Because we all know that a variable or method with static is a class, that is, the class member is stored in the heap memory. So is final the case? After finding the data, it is known that the final protection of the class, methods, variables can not be changed, and does not occupy memory. Therefore, it is not because of the memory relationship.

The real reason is because of the life cycle. The local variable in the method, which is released when the method ends, and final guarantees that the variable always points to an object.

First, the inner class and the outer class are actually at the same level, and the inner class is not destroyed because the definition in the method will follow the execution of the method. The problem is that if the variable in the method of the outer class does not define final, then when the outer class method executes, the local variable must be GC, but a method of the inner class has not been executed, and the external variable that he refers to cannot be found. If defined as Final,java, this variable is copied as a member variable inside the inner class, so that the memory area that the variable points to will not change because the value that is modified by final is always immutable.

One note: The external variables referenced by the inner class must be final

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.