Home > Software engineering >  When is a constructor inherited by subclass
When is a constructor inherited by subclass

Time:11-17

public class A {
    public A() {
        System.out.println("A");
    }
}
public class B extends A{
    public B() {
        System.out.println("B");
    }
}
public static void main(String[] args){
    B b1 = new B();

Output:

A
B

So what's confusing me is, the Inheritance documentation of Java states that:

Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

From my understanding of that, unless you specifically call for super() in the constructor of class B, it should not print A.

So the question is, why does it print A?

CodePudding user response:

The compiler calls the default constructor (no-arg constructor) of the superclass initially from the subclass constructor. So you don't need to explicitly call it. That's why the line is getting printed above.

If you want to call non-default constructor (constructor with arguments) of superclass, then you would have to explicitly call it form subclass.

  • Related