如何定义子 class 继承内部 class 的构造函数?

how to define constructor of a subclass inheriting an inner class?

我正在 Java 学习内在和外在 类。我知道内部和外部 类 是什么以及为什么使用它们。我遇到了关于这个主题的以下问题,但找不到答案。

假设给出以下代码:

class outer{
    class inner{

    }
}

class SubClass extends outer.inner{
}

问题:最小子类构造器应该如何定义?为什么?

Option 1-
Subclass () {
    //reason: bacause the default constructor must always be provided
}
Option 2-
Subclass (Outer outer) {
    //reason : because creating an instance of **Subclass** requires an instance 
    //of outer, which the **Subclass** instance will be bound to
}

Option 3-
Subclass (Outer outer) {
    outer.super();
    //reason : because creating an instance of **Subclass** requires an explicit 
    //call to the **Outer's** constructor, in order to have an enclosing instance 
    //of **Outer** in scope.
}
Option 4- 
Subclass (Outer.inner inner) {
    //reason : bacause an instance of **inner** is necessary so that there is a 
    //source to copy the derived properties from
}

PS。这是一道多项选择题。预计只有 1 个答案

我是 java 的新手,对这些高级主题了解不多

谢谢

这是来自 JLS 的示例,它遵循相同的逻辑,但不传递封闭实例,而是直接在构造函数中创建它:

Example 8.8.7.1-1. Qualified Superclass Constructor Invocation

class Outer {
    class Inner {}
}
class ChildOfInner extends Outer.Inner {
    ChildOfInner() { (new Outer()).super(); }
}

Superclass constructor invocations may be 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.

建议答案中最接近的情况是

public SubClass(Outer outer) {
    outer.super();
}

要扩展作为 Outer 的内部 class 的 Outer.InnerSubClass 构造函数需要具有作为封闭类型的 Outer 的实例.

outer.super(); 将调用 Outer 父 class 的构造函数,即 Inner 构造函数。

outer.super(); 语法可能令人不安,因为我们通常不会在构造函数的参数上调用 super(),但在 class 扩展内部 [=35] 的情况下=], subclass 的构造函数允许这种语法。

我不认为 "outer" class 可以扩展内部 class。该构造意味着,class 可以访问另一个 classes.

的私有成员

你可以有一个内部 class 来扩展同一个外部 class 的另一个内部 class。

至于构造函数,外部实例是在实例化中指定的,而不是作为参数:

class Outer {
   class Inner {
      ...
   }
   class SubInner {
      ...
   }
   void method() {
      Inner i = this.new SubInner();
   }
}