Inheritance in Java – creating an object of the subclass invokes also the constructor of the superclass. Why exactly?

It doesn’t create two objects, only one: B.

When inheriting from another class, you must call super() in your constructor. If you don’t, the compiler will insert that call for you as you can plainly see.

The superclass constructors are called because otherwise the object would be left in an uninitialized state, possibly unbeknownst to the developer of the subclass.

Your subclass actually looks like this after the compiler inserts the super call:

public class B extends A {
    public B() {
        super();
        System.out.println("Bye!");
    }
}

Leave a Comment