【问题标题】:Java: Why does my class automatically inherits constructor from superclass? [duplicate]Java:为什么我的类会自动从超类继承构造函数? [复制]
【发布时间】: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


    【解决方案1】:

    这种行为是由 JLS (§8.8.7. Constructor Body) 规定的:

    如果构造函数体不是以显式构造函数调用开头,并且被声明的构造函数不是原始类Object 的一部分,则构造函数体隐式以超类构造函数调用“super();”开头,即调用不带参数的直接超类的构造函数。

    【讨论】:

      猜你喜欢
      • 2012-01-29
      • 1970-01-01
      • 1970-01-01
      • 2011-11-10
      • 2010-10-04
      • 2018-06-06
      相关资源
      最近更新 更多