Scope of final local variable in java

前端 未结 2 1189
我在风中等你
我在风中等你 2021-01-18 17:07

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 wil

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-18 17:44

    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.

提交回复
热议问题