This content has been marked as final. Show 7 replies
if we have inner class in a method the innerclass instanse does not refer to the method variable.Cannot refer to a local variable in any enclosing scope unless it is final.
it is because the local variable is on stack and inner class instance is on heap.Correct.
And when method complete the stack isCorrect.
destroyed but we can refer the inner class somewhere else and store it or clone it in anyway.
but if we declare the variable final in that case we can refer from innerclasss objectIt is secretly copied. 'final' is there to prevent you changing it in the outer scope, as that won't be reflected in the copy.
how and why?
where it is copied ?Into a secret field in the inner class.
what is that means plz. elaborate itAs you observed, the original variable can disappear with its scope, but the innt class can outlive that scope. So the variable is basically copied into a secret variable of the same name in the inner class. If the original variable wasn't final there would be an implication that changing it would also change the copy. It doesn't. So you are prevented from falling into this trap by having to make the variable final.
GouravBansal wrote:You get to do a number of nice tricks with encapsulation with inner classes (and inner interfaces). The inner class can access the private variables of its enclosing class, and vice versa. Therefore, you can better encapsulate your objects. For example, if I had no inner classes, I would have to create 'helper' classes in the same package. If I wanted to expose a variable in that helper class, I would create package-private accessors (getters). Then, every class in the package would be able to access that class.
One more thing
can u tell me what benifits(OOPS principle) we get creating an inner class rather then a seperate class
which is more easy to understand. why java give concept of inner class.
With inner classes, I can take this one step further. No class could access, say, a private static inner class. Nor would I have to create accessor methods. I can achieve better encapsulation (at the cost of a larger source file containing more lines of code).