我很难理解 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/