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.