The following is the code from K&B in the method-local inner classes chapter
It is said in the book that since 'z' is a method local variable (and hence placed on the stack), it wont be accessible by the inner class. But if we make it a final variable (final String z = "local variable"; ) , then the inner class can access it! How? Is the final variable placed on the heap? Won't it lose its scope once the method finish running? [ February 28, 2007: Message edited by: Binil Benjamin ]
Hi Benjamin, I got your point. I think the fallowing para in K&B makes no sense. 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.
1)How can anybody imagine a Method Local Inner class reference passing out side the method in which its declared. I bet we can not. 2)I don't see any reason why Method Local Inner class can't access Local variables. 3)"First of all the purpose of Method Local Inner classes in not clear."
Anybody who has experimented with Inner classes please respond.
2)I don't see any reason why Method Local Inner class can't access Local variables.
If you agree that point #1 is false, and that you can pass instances of method (and anonymous) inner classes, outside of the method, then you can conclude that it is possible for local variables to go out of scope, when the instance is still in scope.
(Wow, long maybe run-on sentence )
In fact, instances of method inner classes can never access local variables. When the local variable is declared as final, a copy is made for the instance, because it is known to not change.
3)"First of all the purpose of Method Local Inner classes in not clear."
Okay, I will admit it. I am one of those people who abuse the use of anonymous inner classes. It is pretty silly to have a separate class definitions located elsewhere, when the class is only a few lines long, and used in one method.
Never really had the need for method local inner classes, as you can't really do a good job of abuse, if you spread it out ... ... seriously, there is some advantage of method inner classes over anonymous inner classes. The two that I can quickly think of are, you can implement multiple interfaces, and can declare constructors for it.
Joined: Dec 15, 2006
So you mean to say that the compiler will replace the final variable with its constant value, even without considering its scope?
Joined: Feb 15, 2007
Hi Henry Wong,
Great Job. I got the picture clear. Thanks a lot.
subject: Method-local inner class and final local variable