Java Basics-Inner classes-why local and anonymous inner classes can only access local final variables

Source: Internet
Author: User

Let's look at the following code:

 Public classTest { Public Static voidMain (string[] args) {} Public voidTestFinal intb) {Final intA = 10; NewThread () { Public voidrun () {System.out.println (a);            System.out.println (b);        };    }.start (); }}

This code will be compiled into two class files: Test.class and Test1.CLASS。ImpliedRecognizeCiaConditionUnder,CodecTranslatedManagerYesForPunicNameWithinDepartmentClassAndCouncilDepartmentWithin part name ou tt er X.class (x is a positive integer).

As you know, the name of the anonymous inner class in the Test method is test$1.

In the previous code, if either final of the variables A and B is removed, the code compiles. Let's consider this question first:

When the test method is finished, the life cycle of the variable A is over, and the life cycle of the thread object is probably not over yet, then it becomes impossible to continue accessing the variable A in the thread's Run method, but what about the effect? Java uses the means of replication to solve this problem. The bytecode of this code can be deserialized to get the following content:

We see that there is an instruction in the Run method:

Bipush 10

This instruction indicates that the operand 10 is stacked, indicating that a local local variable is being used. This process is performed by the compiler by default during compilation, and if the value of the variable is determined during compilation, the compiler defaults to adding an equal literal to the constant pool in the anonymous inner class (local inner Class) or directly embedding the corresponding bytecode into the execution bytecode. Thus, the variable used by the anonymous inner class is another local variable, except that the value is equal to the value of the local variable in the method, so it is completely independent of the local variable in the method.

  

Let's look at an example below:

 Public class Test {    publicstaticvoid  main (string[] args)  {             }           Public void Test (finalint  a) {        new  Thread () {              Public void run () {                System.out.println (a);}            ;        }. Start ();    }}

The anti-compilation gets:

We see that the constructor for anonymous inner class test$1 contains two parameters, one is a reference to an external class object, and the other is an int variable, and it is clear that the parameter a in the variable test method is passed in as a argument to the copy of the anonymous inner class (copy of variable a) for assignment initialization.

It is also said that if the value of a local variable can be determined during compilation, a copy is created directly inside of the anonymous interior. If the value of the local variable cannot be determined during compilation, the copy is initialized by the way the constructor passes the parameter.

As can be seen from the above, the variable a accessed in the Run method is not the local variable A in the test method at all. This solves the previous problem of inconsistent life cycle. But the new problem comes again, since the variable A in the Run method and the variable A in the test method are not the same variable, what happens when the value of variable A is changed in the Run method?

Yes, it can result in inconsistent data, which will not achieve the original intent and requirements. To solve this problem, the Java compiler restricts the problem of data inconsistency by restricting the variable A to the final variable, not allowing changes to the variable a (which is not allowed to point to the new object for a variable of the reference type).

Here, you should be aware of why local variables and formal parameters in a method must be qualified with final.

Java Basics-Inner classes-why local and anonymous inner classes can only access local final variables

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.