java 为什么有匿名类_java – 为什么匿名类访问封闭类的非最终类成员

在局部变量的情况下,变量的副本是匿名类实例接收到的.因此,局部变量必须做到最终,才能在匿名类中使用,这样它的值可能不会在以后更改.

在封闭类的成员字段的情况下,没有副本.相反,匿名类获取对包围类的引用,从而访问外部类的任何/所有成员字段和方法.所以即使这个字段的值发生变化,这个变化也反映在匿名类中,因为它是相同的引用.

I am confused. We ensure that only a final local variable can be

accessed in anonymous class because we don’t want that the variable

should be out-of-sync between anonymous class and local function. The

same reason should apply to the case if we try to access a non-final

enclosing class member in anonymous class.

如你所见,情况并非如此.复制只适用于局部变量,而不是封闭类的成员字段.原因当然是一个匿名类保留对封闭类的隐含引用,通过该引用,它可以访问任何/所有成员字段&外部类的方法

引用以下链接:

A member variable exists during the lifetime of the enclosing object, so it can be referenced by the inner class instance. A local variable, however, exists only during the method invocation, and is handled differently by the compiler, in that an implicit copy of it is generated as the member of the inner class. Without declaring the local variable final, one could change it, leading to subtle errors due to the inner class still referring to the original value of that variable.

参考文献:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值