4

我正在学习 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 新手,对这些高级主题不太了解

谢谢

4

2 回答 2

2

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

示例 8.8.7.1-1。合格的超类构造函数调用

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

超类构造函数调用可以细分:

  • 不合格的超类构造函数调用以关键字 super 开头(可能以显式类型参数开头)。

  • 合格的超类构造函数调用以 Primary 表达式开头。

它们允许子类构造函数显式指定新创建的对象相对于直接超类的直接封闭实例(第 8.1.3 节)。当超类是内部类时,这可能是必要的

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

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

要扩展 Outer.Inner它的内部类OuterSubClass构造函数需要有一个Outer它是封闭类型的实例。

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

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

于 2017-07-18T12:16:36.223 回答
0

我不认为“外部”类可以扩展内部类。这种结构意味着,一个类可以访问另一个类的私有成员。

不过,您可以有一个内部类来扩展同一个外部类的另一个内部类。

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

class Outer {
   class Inner {
      ...
   }
   class SubInner {
      ...
   }
   void method() {
      Inner i = this.new SubInner();
   }
}
于 2017-07-18T12:22:11.497 回答