gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 03:17:20 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com