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吗?这是我正在阅读的书中的练习题。我不明白。 Inherency对我来说一直是个难题。
答案 0 :(得分:0)
好吧,让我们看看。
首先你打电话给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");
}
同样的事情发生了,首先用它调用另一个构造函数,然后打印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
答案 1 :(得分:0)
按照绳索:
new Circle9();
→
new Circle9(1)
然后print("C")
→
new Circle9(1, white, false)
然后print("D")
然后print("C")
→
new GeometricObject(white, false)
然后print("E")
然后print("D")
然后print("C")
→
print("B")
然后print("E")
然后print("D")
然后print("C")
→
" BEDC"