Java – why do anonymous classes access non final class members of closed classes

We know that the final local variables can only be accessed in anonymous classes. Here is a good reason: Why are only final variables accessible in anonymous class

However, if the variable is a member field of a closed class, I find that anonymous classes can still access non final variables: how can I access enclosing class instance variables from inside the anonymous class?

I'm confused We ensure that the final local variable can only be accessed in anonymous classes, because we don't want variables to lose synchronization between anonymous classes and local functions If we try to access non - final closed class members in anonymous classes, the same reason should apply

Why not a problem?

Solution

In the case of a local variable, a copy of the variable is received by an anonymous class instance Therefore, a local variable must be final before it can be used in an anonymous class, so its value may not change later

In the case of enclosing a member field of a class, there is no copy Instead, an anonymous class gets a reference to the enclosing class to access any / all member fields and methods of the external class So even if the value of this field changes, the change is reflected in the anonymous class because it is the same reference

As you can see, this is not the case Replication applies only to local variables, not to member fields of closed classes The reason, of course, is that an anonymous class retains an implicit reference to the closed class through which it can access any / all member fields & methods of the external class

Reference the following links:

reference:

Why a non-final “local” variable cannot be used inside an inner class,and instead a non-final field of the enclosing class can?.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>