access of non final variable from method local inner class
Praveen Kumar M K
posted 3 years ago
Local inner classes cannot access the local variables defined in the method in which the local classes are defined. the reason is when the local inner class in instantiated , the object as you know is created on the heap. the thing is that this object can have more lifetime than the local variables which defined in the method , which are created on the stack and which once method completes are blown off the stack . so you cannot access local variables from local inner classes. however if you make the variables final, then the local inner classes can access them. this is because , in this case, the object of the inner class gets reference to the local variable that has been declared as final . so even after the method completes the object can access the local variable. the point is that the actual variables has been lost but the reference is there with the inner class object and it seems as if we are accessing the original variable. you can disassemble the class file using javap and you can see the result.