基于 SCJP(EXAM 310-065) 课程的疑问

发布于 2024-09-10 02:54:26 字数 338 浏览 3 评论 0原文

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,但是书上他们说编译失败。谁能解释一下吗?

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(" ");
} }

In the above program, I guessed the output must be BD, but in the book they said the compilation fails. Can anyone explain this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

咽泪装欢 2024-09-17 02:54:26

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

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

请参阅 子类构造函数部分

The derived class Bottom2 is required to call the base class constructor using super, otherwise you'll get a compile error. For example, if you do this, it will compile:

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

See the section on Subclass Constructors.

梦巷 2024-09-17 02:54:26

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

When you have public Top(String s) then java doesn't create the default constructor with no arguments then when you write the child class, the constructor look for the default constructor (because you are not calling explictly)... then the compilations fails.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文