问题描述
Local Inner类不仅可以访问实例变量,还可以访问方法(在其中定义它们的方法)的局部变量,但是必须将局部变量声明为final
.
Local Inner class can not only access the instance variables but local variables of the method (in which they are defined) as well, but the local varible has to be declared final
.
为什么在这种情况下必须将局部变量声明为final
?
Why the local variables have to declared to be final
in this case?
推荐答案
原因是本地内部类的实例可能会从方法中返回,并且在方法返回之后才返回.在这种情况下,访问它们时本地方法变量将不存在.
一旦将它们定义为final,它们实际上是恒定的,因此即使以后也可以安全访问.查看不能在内部类中引用非最终变量以获取更多详细信息.
The reason is that an instance of the local inner class may be returned from the method and last after the method return. In such a case the local method variables won't exist while you access them.
Once you define them as final they are actually constant and therefor safe to access even afterwards.Check out cannot refer to a non final variable inside a inner class for more details.
这篇关于为什么Java内部类要求外部类的变量为final?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!