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

标签 java oop

我知道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/

相关文章:

php - 将参数添加到覆盖方法 E_STRICT 观察

java - 美国/马萨特兰时区无法解析的日期

java - Spring构造函数 Autowiring 和初始化其他字段

jquery - 将类从 Mootools 转换为 jQuery 或经典 javascript

c++ - 将派生类 unique_ptr 分配给基类 unique_ptr

language-agnostic - 这个图案有名字吗?

具有四核处理器的笔记本电脑中的 Java 多线程

java - Android使用服务将通知设置为特定时间

java - 使用 dks KeyStore 类型配置多个 java keystore 时出错

javascript:私有(private)成员和只读属性