Originally posted by Neeraj Kumar Srivastava:
Local variables of the method live on the stack, and exist only for the lifetime of the method. Thus scope of the local variable is limited to lifetime of the method. But the Inner class objects,created on the heap, might still be alive even after the method completes. (for ex a reference to it was passed to other code).
This complication prevents method local variables from being used by the Method Local Inner Class unless the variable are marked final
This is incorrect. An analysis of the generated code will show that this is not true. Variables are passed to inner classes the same way that parameters are passed to any method.
Let's look at the common wisdom from above. The same potential problem would exist if you were passing parameters to any method and they were used in a thread for example that outlived the calling method! Parameters are always passed by value in
Java so when they are passed copies are made. The same goes for inner classes. Copies are made and given to the inner class so there is no problem with stack variables expiring.