java中局部变量,Java中最终局部变量的范围

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?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值