Why do we use final keyword with anonymous inner classes?
Asked Answered
G

2

24

I'm currently preparing the S(O)CJP, with the Sierra & Bates book.

About inner classes (method local or anonymous), they say that we can't access the local variables because they live on the stack while the class lives on the heap and could get returned by the method and then try to have access to these variables that are on the stack but do not exist anymore since the method has ended...

As we all know, we can bypass this by using the final keyword. This is what they say in the book but they don't really explain what's the effect of that final keyword... As far as i know, using the final keyword on a method local variable doesn't make it live on the heap... So how would the class be able to access a final variable that still lives on the stack while there could be no more stack???

I guess there should be some kind of "copy" of this final local variable inside the inner class. Since the value can't change, why not duplicating this information... Can someone confirm this or tell me if i'm missing something?

Googolplex answered 16/8, 2011 at 10:28 Comment(0)
V
19

Your intuition is correct, because the variable is final it is safe to make a copy of it. Of course for reference types this means copying the reference to the object and not the object it refers to.

Virgo answered 16/8, 2011 at 10:32 Comment(0)
P
12

The compiler uses subtle trickery copying the final reference under the covers to let the inner class get to the final field in the outer class. The copying is why the field must be final so the value does not change.

See e.g. http://tech-read.com/2008/06/19/why-inner-class-can-access-only-final-variable/

Plantation answered 16/8, 2011 at 10:40 Comment(2)
Yes but the compiler could still copy the variable even if it wasn't final. My guess is that requiring it to be final makes the code more explicit that it won't change.Dino
The problem - to my understanding - is that if you do not require it to be final, you need to keep much more careful track of handling this and updating whenever the outer variable changes. What if you have numerous instances of the inner class and they all need to be updated?Rainer

© 2022 - 2024 — McMap. All rights reserved.