Writing a multithreaded program today, discovering that inside a method defines an inner class, if the inner class calls the variable in the method, then the variable must be declared as the final type, baffled, and then thought of as the cause of the life cycle, because the variable defined in the method is a local variable, leaving the method, the variable loses its function , it will automatically be eliminated, but the inner class will not leave its method to lose its function, it has a broader life cycle, the following is illustrated by an example:
As shown in the example, an inner class timerprint is declared in the Outer class outer, and the method in this class refers to a local variable in the method start Testtxt
Logically: Because the inner class appears inside a method, but when actually compiled, the inner class is compiled to Outer$1timerprint.class, which means that this method of the outer class is at the same level as the inner class. In other words, the life cycle of a non-final variable and an inner class is different! When start is called, the non-final variable disappears, and an internal class reference is illegal!
Practice: The Java compiler behaves like this (provided the variable is referenced in an inner class):
If it is defined as final, the Java compiler generates a copy of the external variable within the inner class timerprint, and can guarantee that the inner class can reference the external property and that the value is unique.
If it is not defined as final, it cannot be compiled! ( jdk1.6 tested). Because the compiler does not copy non-final variables, the variables referenced by the inner class are illegal!
Here's a look at the compiled byte code:
Post-compiled bytecode for external classes:
internal Class-compiled bytecode:
If the variable d in the outer class is not referenced by the inner class, final is optional, and the Java compiler will not do special processing!!
Add a parameter D and define it as a non-final type, after compiling the following file:
the compiled external class:
Compiled internal class:
As can be seen, internal classes are defined inside a method, if the inner class calls the variable inside the method, the variable must be final decorated, or else it will be given an error because the variable being used cannot be found when calling the inner class!
Article quoted---blog.csdn.net/zzp_403184692/article/details/8014235
Why a local variable in a Java inner class references an external class must be a final problem resolution