Why must the anonymous internal class parameter be of the final type?

Source: Internet
Author: User

First, this is related to the lifecycle of Java objects.

When the basic data type and the referenced variable (not the referenced object) are used as local variables (this is different from the variable member variables, they are part of the object as member variables and have the same lifecycle as the object). Their lifecycle is scoped and is not affected by the lifecycle, however, the lifecycle of objects created in the same scope is not limited by the scope.

 

The lifecycle of a local variable is inconsistent with that of an object of a local internal class.

 

When a local variable of an external class is used in an internal class, it is actually called by an internal Class Object in its life cycle, when the internal class tries to access the local variables in the external method, the local variables of the external method may no longer exist, so we have to continue its life and copy it to the internal class, however, copying will bring about inconsistency, and thus the final statement must be used to ensure consistency.

 

Replication ensures that the lifecycle is continued, and final ensures that the reference is consistent.

 

References:

Http://lionheartyd.iteye.com/blog/1472407

Http://bbs.csdn.net/topics/300068105

 

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.