Java: Why does my class automatically inherits constructor from superclass? [duplicate]

百般思念 提交于 2019-12-23 06:13:42

问题


When I try the code on the bottom of this question, the output is:

a a b a b c

So this means that the constructor from B and C call the constructors from their superclasses. But why? I thought that the superclass' constructor only get's called when used with the super() function like this:

public sportscar(String name, int weight, int topspeed){
    super(name, weight);
    this.setTopspeed(topspeed);
}

But if it automatically takes over the constructor from the classes they extend from, why would we use the super() function? I know that normal methods extend to there sub-classes automaticaly, but I thought that the constructor was different.

If anyone can clear this out for me, thanks a lot!

Code:

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

回答1:


This behaviour is mandated by the JLS (§8.8.7. Constructor Body):

If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.



来源:https://stackoverflow.com/questions/23899863/java-why-does-my-class-automatically-inherits-constructor-from-superclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!