gpt4 book ai didi

java - java中外部类和内部类是如何关联的?

转载 作者:行者123 更新时间:2023-11-30 01:44:17 26 4
gpt4 key购买 nike

我知道java中内部类的每个实例都与其外部类的一个实例相关联,但我想知道这个过程是如何进行的。

更具体地说,当你写下类似的内容时

public class Outer {
Inner root;

class Inner {
public Inner() {
next = (Math.random() > 0.5)? new Inner(): null;
}

Inner next;
}
}


rootroot.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 let i be the instance being created. If C is an inner class, then i may have an immediately enclosing instance (§8.1.3), determined as follows:

  • [...]
  • 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 let O be the immediately enclosing class of which C is a member. Let n be an integer such that O 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 of this.

      • Otherwise, a compile-time error occurs.

换句话说,当你执行时

next = (Math.random() > 0.5)? new Inner(): null;

Inner正在实例化的类; Inner是包含该类的类的成员( Inner ,即其本身)​​,其中 new Inner()出现; OuterInner 的直接封闭类;因为InnerOuter 的内部类,必须有一个 thisthis保证有 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com