Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it's impossible in java to refer non-final variable in inner anonymous class? [duplicate]

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.

like image 900
dhblah Avatar asked Jul 12 '11 10:07

dhblah


1 Answers

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.

like image 91
Mathias Schwarz Avatar answered Sep 22 '22 08:09

Mathias Schwarz