Why a method-local inner class can't use variables declared inside the enclosing method except those marked final, i know that the variables declared inside the enclosing method might vanishes while the inner class instance remains valid, but what has changed when this variable/s is declared final?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
The reason is [ Actually Conclusion from Where are Java final local variables stored? ] :
final variables are copied by the compiler into a hidden member variable of the inner class that references it. This way, they are guaranteed to not change after the copy has been made.
Also might be : The Method-Local Inner Class which is on the heap and the variable which is on the stack have different scope. But if the local variable is marked by final, it is stored on the heap.
Now at first i would like to light upon
So now think about it.The local variables of the method live on the stack and exist only for the lifetime of the method. We already know that the scope of a local variable is limited to the method the variable is declared in. When the method ends, the stack frame is blown away and the variable is history. But even after the method completes, the inner class object created within it might still be alive on the heap if, for example, a reference to it was passed into some other code and then stored in an instance variable. Because the local variables aren't guaranteed to be alive as long as the method local inner class object is, the inner class object can't use them. Unless the local variables are marked final. And it is beneficial making variable final as it can remain like synthetic field.
The reason is that it is specified in the Java Language Specification #8.1.3
Also note that project lambda (java 8), which aims at introducing closures in java (to replace anonymous classes), introduces the notion of effectively final which will allow you to use a non final variable within a lambda expression as long as you don't modify it within the closure.
When the variable is final, a copy is placed in the inner class. i.e. it still can't access the variable, but it has a copy it can use.
You can see these copies if you use reflection or with a debugger.
Final ensures that you won't lose the reference to that variable. You don't want your inner class to destroy or lose your reference since you might continue using it in the context where was declared.