Java learning question (1)-Why cannot I directly access local variables in a local internal class? It must be modified to final for direct access.

Source: Internet
Author: User

Recently, an anonymous internal class was used to implement the jtextfield listening character length function. Two local variables were referenced in the class. An error occurred during compilation and the class "must be declared as the final type" was reported ", I am confused, so I am searching for the reason on the Internet. Here I will summarize it.

 

The local variable in the method cannot be directly accessed in the local internal class (the class defined inside the method), and must be modified as final.

1: the life cycle of a variable is inconsistent with that of an object in a local internal class, which leads to this problem. After a method is run, its local variables are recycled, the end of an object's lifecycle is not here. It is recycled only when the object is no longer referenced. If internal classes can directly access local variables, there may be a phenomenon:The object is accessing a non-existent variable.

 

2: we assume that the local variables in the method can be directly accessed in the local internal class without final type. We know that the access variable in the internal class is actually accessing the replica of the variable. If the above conditions are true, whether it is the basic type or the reference type, once the entity or replica of a local variable changes, it cannot be synchronized with each other. As a result, the object of the variable is inconsistent with that of the replica. Imagine that you are accessing a variable, however, the value you get is different from the actual value, so it is meaningless.

 

In a certain sense, this is a weakness of the Java language. The design of the programming language is restricted by the implementation technology. In the future, we hope that the technology will continue to develop and this restriction can be solved.

Related Article

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.