We know that only final local variables can be accessed in an anonymous class, and there is a good reason here: Why are only final variables accessible in anonymous class?.
However, I found that an anonymous class can still access a non-final variable if the variable is an member field of the enclosing class: How can I access enclosing class instance variables from inside the anonymous class?
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.
Why would it not be a concern?
In the case of a local variable, a copy of the variable is what the anonymous class instance receives. For this reason, the local variable has to be made final
before it can be used within the anonymous class, so that its value may not change later.
In the case of a member field of the enclosing class, there is no copy. Rather, the anonymous class gets a reference to the enclosing class, and thereby it accesses any/all member fields and methods of the outer class. So even if the value of the field changes, the change is reflected in the anonymous class as well, because it is the same reference.
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.
As you see, that is not the case. The copying happens only for local variables, not for member fields of the enclosing class. The reason is, of course, that an anonymous class holds an implicit reference to the enclosing class, and through that reference it can access any/all member fields & methods of the outer class.
To quote the link below:
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.
References:
1. Why a non-final “local” variable cannot be used inside an inner class, and instead a non-final field of the enclosing class can?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With