A method local inner class cannot access method local variables bcoz they are on stack and might be short lived as compared to the instance of the method local inner class.
But then the method local inner class can access method local variables marked "final". Does marking a method local variable "final" put it on heap or increase its life beyond the method execution ?...If so how?
[ February 26, 2007: Message edited by: meg jos ] [ February 27, 2007: Message edited by: megha joshi ]
Hi Jesse, so far i think dat the reason given by meg is the only reason why local variables of method can't be accessed within method local inner class but by reading the post to which you have given the link, it seems that the reson why we cannot access local variables from method local inner class is that its a BAD THING (metioned in that post) as there is copy of local variable stored in private variable of inner class which can be modified if the local variable is not declared final, therefore java enforces the programmer to mark local variable as final variable.
So what is the true reason that prevents us to access method local variables within method local inner class ??
First of all, this is all speculation on my side. I'm just trying to think logically about this.
We know method local inner classes can't access the method variables because of the scoping problems that can occur. A solution would be to give the inner class copies of the local method variables. But now we face a new problem. If we change the value of one of the local method variables, the copy that exists in the inner class doesn't have the same value any more. This would be a reason for the requirement of making them final if you want to use them in the inner class.
Actually everyone is diverging from my question and telling me what I already know.
Please see that what I asked is why are final variables OK in inner class?Are they longer lived then method?Are they on heap?How is their life or storage different from local variables which cant be used in inner class
Actually the the local variables are copied to the inner class. So if the value of the local variable changes ... that will be a problem. Thats why it only allows the final variables to be copied to the heap, since they cannot be changed in the future.
have you even read the answers posted here thoroughly? We have exactly addressed your issue. Marking a variable as final does not widen it's scope in any way! The only reason inner classes have acces to final variables is because they hold a copy of those vaiables. And because it's a copy it has to be final to prevent inconsistent data.
A day job? In an office? My worst nightmare! Comfort me tiny ad!