2016-03-02 106 views
-4
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解释一下吗?这是我正在阅读的一本书的练习题。我不明白。对于我来说,内在是一个很难的话题。需要帮助理解这个代码的输出。

+5

我投票关闭这一问题作为题外话,因为“解释我这一切”不是一个具体的问题陈述。通过手动或调试器来浏览代码,了解多态性是如何工作的,如何更彻底地阅读您的书籍,如果在此之后仍然存在一个非常具体的问题,请发布一个新问题。我们不是在这里解释整个主题。 –

回答

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,最后ç

输出应该BEDC

+0

干杯的朋友。这就是我需要的! –

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”