Inner class and local variables

后端 未结 6 560
无人共我
无人共我 2020-11-30 12:48

Why do I need to declare a local variable as final if my Inner class defined within the method needs to use it ?

Example :

6条回答
  •  情话喂你
    2020-11-30 13:11

    Local variables always live on the stack, the moment method is over all local variables are gone.

    But your inner class objects might be on heap even after the method is over (Say an instance variable holds on to the reference), so in that case it cannot access your local variables since they are gone, unless you mark them as final

提交回复
热议问题