天天看点

java内部类访问外部类变量 final,为什么Java内部类要求外部类的变量为final?

java内部类访问外部类变量 final,为什么Java内部类要求外部类的变量为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.

Why the local variables have to declared to be final in this case?

解决方案

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.