Possible Duplicate:
Cannot refer to a non-final variable inside an inner class defined in a different method
Why it's impossible in java to refer non-final variable in inner anonymous class? Simple answer would be "Because it's prohibited", but I'd like to know, WHY did they prohibit this useful functionality? Maybe there are some sort of abilities Java lacks of or it's designed in the "wrong" way. I'd like to know.
The reason is that after the enclosing method returns, the local variable no longer exists. Therefore a copy of the variable is created when the anonymous class is instanciated. If Java allowed the local variable to be changed afterwards, the anonymous class would only know the old value.
The way Java does it is opposed to real closures known from other languages.
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