Previously wrote a project, long time no update, recently turned up the previous code, found here reported a mistake. (now go to IntelliJ, once in Eclipse Luna can be compiled, Eclipse Mars will also error, JDK version is 1.8, not to check why)
Why is it necessary to declare an external variable in an inner class as final?
At first I was thinking about the memory model of Java. Because we all know that a variable or method with static is a class, that is, the class member is stored in the heap memory. So is final the case? After finding the data, it is known that the final protection of the class, methods, variables can not be changed, and does not occupy memory. Therefore, it is not because of the memory relationship.
The real reason is because of the life cycle. The local variable in the method, which is released when the method ends, and final guarantees that the variable always points to an object.
First, the inner class and the outer class are actually at the same level, and the inner class is not destroyed because the definition in the method will follow the execution of the method. The problem is that if the variable in the method of the outer class does not define final, then when the outer class method executes, the local variable must be GC, but a method of the inner class has not been executed, and the external variable that he refers to cannot be found. If defined as Final,java, this variable is copied as a member variable inside the inner class, so that the memory area that the variable points to will not change because the value that is modified by final is always immutable.
One note: The external variables referenced by the inner class must be final