Why Java Inner Classes require variables of outer

2019-06-13 18:10发布

问题:

Possible Duplicate:
Java - inner class and local variables
How does marking a variable as final allow inner classes to access them?

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?

回答1:

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.



回答2:

You are talking about anonymous classes. Local variable (only) must be final to be referenced by their implementations, because the code may execute in an unknown execution frame, possibly also in another thread, so the compiler's only hope to use a value is if it's a constant at the time the anonymous class is instantiated (declared) - ie if the variable is final.



标签: java final