Scope of final local variable in java

对着背影说爱祢 提交于 2019-12-19 17:47:23

问题


Method-Local inner class cannot access local variables because the instance of the method-local inner class may still alive after the method is over. But local variables will vanish once the local method is over. I learned that method-local inner class can access final local variable, does this mean final local variable still alive after the method is over?


回答1:


Sort of. Java anonymous inner classes act like "closures," that is, they "close" around the current local state. However, Java only lets these classes close around final variables. If it didn't, the local state of the variable could change, but the version held in the inner class would not, so it would be accessing an "out of date" instance. This could be confusing to a programmer.

Instead, Java requires that mutability be handled by the instance through methods, not variable reassignment. This leads to better clarity and allows for simpler debugging. For more information about why Java does this, see this answer.

Since the class still holds a reference to the variable, the answer to your question is yes, that instance will not be garbage collected until the inner class relinquishes ownership of the variable.




回答2:


No it doesn't. It means that a copy of the local variable is still alive, in the inner class instance. The 'final' just makes sure the two copies don't confusingly diverge in value.



来源:https://stackoverflow.com/questions/10669993/scope-of-final-local-variable-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!