Java:非静态嵌套类和 instance.super()

标签 java inner-classes

我很难理解 Java 中的非静态嵌套类。考虑以下示例,它打印“Inner”,然后打印“Child”。

class Outer {
    class Inner {
        Inner() { System.out.println("Inner"); }
    }
}

public class Child extends Outer.Inner {
    Child(Outer o) {
        o.super();
        System.out.println("Child");
    }
    public static void main(String args[]) {
        new Child(new Outer());
    }
}

我知道 Inner 的实例总是必须与 Outer 实例相关联,这也适用于 Child,因为它扩展了 Inner。我的问题是 o.super() 语法的含义 - 为什么它调用内部构造函数?

我只看到一个普通的 super(args) 用于调用父类(super class)构造函数和 super.method() 调用父类(super class)版本的重写方法,但绝不是 instance.super() 形式的东西。

最佳答案

它被称为“合格的父类(super class)构造函数调用”。

引自 here :

Explicit constructor invocation statements can be divided into two kinds:

  • Alternate constructor invocations begin with the keyword this (possibly prefaced with explicit type arguments). They are used to invoke an alternate constructor of the same class.

  • Superclass constructor invocations begin with either the keyword super (possibly prefaced with explicit type arguments) or a Primary expression. They are used to invoke a constructor of the direct superclass. Superclass constructor invocations may be further subdivided:

  • Unqualified superclass constructor invocations begin with the keyword super (possibly prefaced with explicit type arguments).

  • Qualified superclass constructor invocations begin with a Primary expression . They allow a subclass constructor to explicitly specify the newly created object's immediately enclosing instance with respect to the direct superclass (§8.1.3). This may be necessary when the superclass is an inner class.

关于Java:非静态嵌套类和 instance.super(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2831484/

相关文章:

java - 在设置了*中断状态*的情况下调用 Thread.sleep()?

java - 将 EhCache 磁盘存储内容加载到内存中

java - 当部署在 Websphere Liberty Profile 中时,Spring Boot 仅在第一个请求中初始化上下文

java - 封闭类的内部类成员的可访问性

c# - 其参数扩展嵌套类的泛型类

java - Spring应用的集成测试

java - Android GridView 重绘问题

Javascript对象聚合: cannot call method of inner object

Clojure 导入嵌套类

c++ - 将 Exception 创建为内部类是个好主意吗? C++