Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When is a constructor inherited by subclass

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading