java - 如何定义继承内部类的子类的构造函数?

标签 java inheritance constructor inner-classes outer-classes

我正在学习 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
}

附言。这是一道多项选择题。预计只有 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 的内部类的 Outer.InnerSubClass 构造函数需要有一个 Outer< 的实例 这是封闭类型。

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

outer.super(); 语法可能令人不安,因为我们通常不会在构造函数的参数上调用 super(),但在类扩展内部类,子类的构造函数允许这种语法。

关于java - 如何定义继承内部类的子类的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45166315/

相关文章:

c# - 在继承自基页的页面上查找控件

C#继承/多态

JavaScript 匿名构造函数 : ! function(){}();

java - 如何在Java中使用indexOf

java - 解析包含右侧带有减号的数字的字符串

java - 检查数组是否包含超过 1 个等值(value)

c++ - C++11有规定静态/全局变量的构造顺序吗?

java - 如何使用ExtJs向服务器发送参数?

java - 关于Java动态类型的问题

android - 错误: The Constructor File(URI) is undefined