我知道java中内部类的每个实例都与其外部类的一个实例相关联,但我想知道这个过程是如何进行的。
更具体地说,当你写下类似的内容时
public class Outer {
Inner root;
class Inner {
public Inner() {
next = (Math.random() > 0.5)? new Inner(): null;
}
Inner next;
}
}
root
、root.next
等...如何与同一个 Outer
实例关联?编译器是否向内部构造函数添加参数?
最佳答案
How are root, root.next, etc... all associated with the same instance of
Outer
?
Java Language Specification section on Determining Enclosing Instances在类实例创建期间状态:
Let
C
be the class being instantiated, and leti
be the instance being created. IfC
is an inner class, theni
may have an immediately enclosing instance (§8.1.3), determined as follows:block 引用>
- [...]
- If
C
is an inner member class, then:
- If the class instance creation expression is unqualified, then:
- If the class instance creation expression occurs in a static context, then a compile-time error occurs.
Otherwise, if
C
is a member of a class enclosing the class in which the class instance creation expression appears, then letO
be the immediately enclosing class of whichC
is a member. Letn
be an integer such thatO
is the n'th lexically enclosing type declaration of the class in which the class instance creation expression appears.The immediately enclosing instance of
i
is the n'th lexically enclosing instance ofthis
.- Otherwise, a compile-time error occurs.
换句话说,当你执行时
next = (Math.random() > 0.5)? new Inner(): null;
Inner
正在实例化的类;Inner
是包含该类的类的成员(Inner
,即其本身),其中new Inner()
出现;Outer
是Inner
的直接封闭类;因为Inner
是Outer
的内部类,必须有一个this
那this
保证有Outer
封闭实例;最后,该封闭实例成为i
的封闭实例,新Inner
正在创建实例。简而言之,它重用了
Outer
的同一个实例。 。Does the compiler add a parameter to the
Inner
constructor?Java Language Specification section on the Formal Parameters of Constructors状态:
The constructor of a non-private inner member class implicitly declares, as the first formal parameter, a variable representing the immediately enclosing instance of the class (§15.9.2, §15.9.3).
所以,是的。
关于java - java中外部类和内部类是如何关联的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58738518/