Must Inner classes have a reference to the enclosed class?

ⅰ亾dé卋堺 提交于 2019-12-02 08:42:49
stevevls

A non-static nested class always holds a reference to the enclosing class. In your example, you can reference the enclosing class from Inner as Enclosing.this.

JLS 8.1.3 "Inner classes and Enclosing Instances":

"An instance i of a direct inner class C of a class O is associated with an instance of O, known as the immediately enclosing instance of i. The immediately enclosing instance of an object, if any, is determined when the object is created (§15.9.2)."

Paulo Viana

Yes. An inner class (or non-static nested class) is just like any other instance member of the outer class, and as such always needs a reference of the enclosing class.

Where does it say that an inner class always holds a reference to the outer class?

In the same place it defines the Outer.this syntax. The existence of this syntax is the existence of the reference. There is nothing to suggest that it is suppressed if not used.

Abhishekkumar

There are two cases of nested-classes:

static nested-classes. The nested-class does not keep reference to the outer-class.

non-static nested-classes. The nested-class does keep a reference to the outer-class.

The case of a static nested-class that extends the outer-class is not as interesting as the non-static nested-class extending the outer-class.

An important thing to remember is that non static nested classes are simply called inner classes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!