【问题标题】:Need help understanding the output of this code. [closed]需要帮助理解此代码的输出。 [关闭]
【发布时间】:2016-03-02 21:42:26
【问题描述】:
What is the output of running class Test?

public class Test {
 public static void main(String[] args) {
  new Circle9();
 }
}

public abstract class GeometricObject {
  protected GeometricObject() {
    System.out.print("A");
  }

  protected GeometricObject(String color, boolean filled) {
    System.out.print("B");
  }
}

public class Circle9 extends GeometricObject {
  /** No-arg constructor */
  public Circle9() {
    this(1.0);
    System.out.print("C");
  }

  /** Construct circle with a specified radius */
  public Circle9(double radius) {
    this(radius, "white", false);
    System.out.print("D");
  }

  /** Construct a circle with specified radius, filled, and color */
  public Circle9(double radius, String color, boolean filled) {
    super(color, filled);
    System.out.print("E");
  }
}

谁能详细解释一下为什么这段代码的输出是 BEDC?这是我正在阅读的书中的练习题。我不明白。对我来说,内在性一直是个难题。

【问题讨论】:

  • 我投票决定将此问题作为题外话结束,因为“向我解释这一切”不是一个具体的问题陈述。手动或使用调试器检查您的代码,了解多态性是如何工作的,更彻底地阅读您的书,如果在那之后您仍然有一个非常具体的问题,请发布一个新问题。我们不是在这里解释整个主题。

标签: java inheritance abstract-class


【解决方案1】:

好吧,让我们看看。

首先你调用 Circle9()

启动构造函数:

/** No-arg constructor */
public Circle9() {
this(1.0);
System.out.print("C");
}

如你所见,构造函数首先调用this(1.0)

这意味着打开了另一个构造函数,之后我们打印“C”

好吧,下一个构造函数是:

public Circle9(double radius) {
this(radius, "white", false);
System.out.print("D");
}

同样的事情发生了,首先用 this 调用另一个构造函数,然后打印 D

下一个被调用的构造函数是:

public Circle9(double radius, String color, boolean filled) {
super(color, filled);
System.out.print("E");
}

这调用了一个超级构造函数。由于 Circle9 扩展了 GeometricObject,它可以使用 GeometricObject 函数。所以super(color,filled) 打电话

protected GeometricObject(String color, boolean filled) {
System.out.print("B");
}

然后打印 B,然后是之前的 E,然后是 D,​​最后是 C

输出应该是 BEDC

【讨论】:

  • 干杯朋友。这就是我所需要的!
【解决方案2】:

跟着绳子走:

new Circle9();
new Circle9(1) 然后print("C")
new Circle9(1, white, false) 然后print("D") 然后print("C")
new GeometricObject(white, false) 然后print("E") 然后@9876543329@ 然后@98764 @ →
print("B")然后print("E") 然后print("D") 然后print("C")
“BEDC”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多