基于 SCJP(EXAM 310-065) 课程的疑问
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
派生类
Bottom2
需要使用super
调用基类构造函数,否则会出现编译错误。例如,如果您这样做,它将编译:请参阅 子类构造函数部分。
The derived class
Bottom2
is required to call the base class constructor usingsuper
, otherwise you'll get a compile error. For example, if you do this, it will compile:See the section on Subclass Constructors.
当你有 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.