问题
I have an inner class (non-static) which is using a reference to an enclosing class in its initialization. Will the inner class keep a reference to the enclosing class now?
class Enclosing {
class Inner {
private final ABC innerField = outerField.computeSomething();
}
private final XYZ outerField = something();
}
UPDATE
I am very much aware that one can reference the outer class with Enclosing.this
.
But, if the class doesn't use the reference, must the reference be there after compilation? Is it necessary even if the reference is only used in the initialization?
Where does it say that an inner class always holds a reference to the outer class?
回答1:
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)."
回答2:
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.
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/13145887/must-inner-classes-have-a-reference-to-the-enclosed-class