Why is it not possible in java to specify a non-final variable in an internal anonymous class?

Possible duplicate:
You cannot reference a non-finite variable inside an inner class defined in another way

Why is it impossible in java to reference a non-final variable in an internal anonymous class? The simple answer would be “Because it is forbidden,” but I would like to know WHY they have forbidden this useful functionality? Perhaps there are some abilities that Java lacks, or they were developed "incorrectly." I would like to know.

+6
source share
1 answer

The reason is that after the environment method returns, the local variable no longer exists. Therefore, a copy of the variable is created when the anonymous class is instantiated. If Java allowed the local variable to be subsequently changed, the anonymous class would only know the old value.

The way Java contradicts real closures known in other languages.

+3
source

Source: https://habr.com/ru/post/892564/


All Articles