【发布时间】:2015-06-11 06:46:10
【问题描述】:
我们知道在匿名类中只能访问 final 局部变量,这里有一个很好的理由:Why are only final variables accessible in anonymous class?。
但是,我发现如果变量是封闭类的成员字段,匿名类仍然可以访问非 final 变量:How can I access enclosing class instance variables from inside the anonymous class?
我很困惑。我们确保在匿名类中只能访问最终的局部变量,因为我们不希望该变量在匿名类和局部函数之间不同步。如果我们尝试访问匿名类中的非最终封闭类成员,同样的原因应该适用于这种情况。
为什么不用担心?
【问题讨论】:
-
The same reason could apply to the case if we try to access non-final instance variable in anonymous class..... 这被称为从对象的引用中访问对象的字段。为什么对象的起源或其类的声明很重要? -
@user2499800:你看到我的回答了吗?你在哪里接触到这个?如果您回复,将不胜感激... :)
标签: java closures final anonymous-class