-1

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 ");
    }
}
S. Tanghe
  • 97
  • 1
  • 7

1 Answers1

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012