加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 16:21:49 所属栏目:Java 来源:网络整理
导读:我们知道只能在匿名类中访问最终的局部变量,这里有一个很好的理由: Why are only final variables accessible in anonymous class?. 但是,如果变量是封闭类的成员字段,我发现匿名类仍然可以访问非最终变量:How can I access enclosing class instance vari
我们知道只能在匿名类中访问最终的局部变量,这里有一个很好的理由: Why are only final variables accessible in anonymous class?.

但是,如果变量是封闭类的成员字段,我发现匿名类仍然可以访问非最终变量:How can I access enclosing class instance variables from inside the anonymous class?

我很困惑.我们确保只能在匿名类中访问最终的局部变量,因为我们不希望变量应该在匿名类和本地函数之间失去同步.如果我们尝试在匿名类中访问非最终的封闭类成员,那么同样的原因应该适用于这种情况.

为什么不是一个问题?

解决方法

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

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

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.

参考文献:

Why a non-final “local” variable cannot be used inside an inner class,and instead a non-final field of the enclosing class can?.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读