The inner class object cannot use the local variables of the method the inner class is in.
Because the local variables aren't guaranteed to be alive as long as the method-local inner class object, the inner class object can't use them. Unless the lcoal variables are marked final.
This message was edited 1 time. Last update was at by jose chiramal
jose chiramal
Ranch Hand
Joined: Feb 12, 2010
Posts: 261
posted
0
One more question to add to this :
Page 672 K&B :
"You can't for example mark method-local inner class public,private, protected, static, transient and the like. -- Why so ?
For the purpose of the exam, the only modifiers you can apply to a method-local inner class are abstract and final".
1. Since the variable is final in the method, so the local class gets a copy of the variable. When an instance of the local class is created, it gets a copy of the final variables of the enclosing method. There is no problem with this as we know that the value of final variables cannot be changed, so the copy of the final variable that the local class has is always same as the value of the final variable in the method.
2. What is the use of marking any declaration inside a method private or protected or static?? The declarations in a method are available only inside the method, so marking them public or private is useless...
I tried to run your code with the outer variable 'x' as final and didn't get any error.?
got this output:
Outer x is :Outer2
local variable z is:local variable
You cannot access a variable inside method unless its final, since in that case each method invocation will have to keep its own instance of local variable.