1
class Top{
public Top(String s){System.out.print("B");}
}

public class Bottom2 extends Top{
    public Bottom2(String s){System.out.print("D");}
    public static void main(String args[]){
        new Bottom2("C");
        System.out.println(" ");
} }

在上面的程序中,我猜输出一定是BD,但在书中他们说编译失败。谁能解释一下?

4

2 回答 2

3

派生类Bottom2需要使用 调用基类构造函数super,否则会出现编译错误。例如,如果你这样做,它将编译:

public Bottom2(String s) { super(s); System.out.print("D"); }

请参阅子类构造函数部分

于 2010-07-13T03:35:49.783 回答
2

当你有 public Top(String s) 然后java不会创建没有参数的默认构造函数然后当你编写子类时,构造函数会查找默认构造函数(因为你没有显式调用)......然后编译失败。

于 2010-07-13T03:36:58.890 回答