在局部变量的情况下,变量的副本是匿名类实例接收到的.因此,局部变量必须做到最终,才能在匿名类中使用,这样它的值可能不会在以后更改.
在封闭类的成员字段的情况下,没有副本.相反,匿名类获取对包围类的引用,从而访问外部类的任何/所有成员字段和方法.所以即使这个字段的值发生变化,这个变化也反映在匿名类中,因为它是相同的引用.
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.
参考文献: