Scope of final local variable in java

Method. A local inner class cannot access local variables, because an instance of a local inner method of a method can remain alive after the method completes. But local variables will disappear after completion of the local method. I found out that a method-local inner class can access the final local variable, does this mean that the final local variable is still alive after the method finishes?

+6
source share
2 answers

Grade. Java-anonymous inner classes act like a “close”, meaning they “close” around the current local state. However, Java only allows these classes to close around finite variables. If this is not the case, the local state of the variable may change, but the version contained in the inner class will not, so it will refer to the "deprecated" instance. This may confuse the programmer.

Instead, Java requires that mutation be handled by the instance using methods, rather than a remapping variable. This leads to greater clarity and simplifies debugging. For more information on why Java does this, see this answer .

Since the class still contains a variable reference, the answer to your question is yes, this instance will not be garbage collected until the inner class relinquishes ownership of this variable.

+7
source

No no. This means that the copy of the local variable is still alive in the internal instance of the class. The “finale” simply ensures that the two copies do not ridiculously diverge in value.

+1
source

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


All Articles