【发布时间】:2014-07-16 23:35:09
【问题描述】:
当我尝试这个问题底部的代码时,输出是:
a a b a b c
所以这意味着 B 和 C 的构造函数从它们的超类调用构造函数。但为什么? 我认为只有在与 super() 函数一起使用时才会调用超类的构造函数,如下所示:
public sportscar(String name, int weight, int topspeed){
super(name, weight);
this.setTopspeed(topspeed);
}
但如果它自动从它们扩展的类中接管构造函数,我们为什么要使用 super() 函数?我知道普通方法会自动扩展到那里的子类,但我认为构造函数是不同的。
如果有人能帮我解决这个问题,非常感谢!
代码:
public class App {
public static void main(String[] args) {
new A();
new B();
new C();
}
}
public class A {
public A(){
System.out.println("a ");
}
}
public class B extends A {
public B(){
System.out.println("b ");
}
}
public class C extends B {
public C(){
System.out.println("c ");
}
}
【问题讨论】:
标签: java inheritance constructor