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

user42155 picture user42155 · Jan 28, 2009 · Viewed 33.7k times · Source

I have a question about inheritance in Java.

I have two classes A and B , and class B, inherits from A:

public class A {
     public A() {
         System.out.println("Hi!");
     }
}


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

     public static void main(String[] args) {
         B b = new B();
     }
}

When I run program B, the output is:

Hi!
Bye!

Question : why the constructor of class A is invoked, when I create and object of class B ?

I know that B inherits everything from A - all instance or class variables, and all methods, and in this sense an object of B has all characteristics of A plus some other characteristics defined in B. However, I didn't know and didn't imagine that when I create an object of type B, the constructor of A is also invoked. So, writing this:

B b = new B();

creates Two objects - one of type B, and one of type A.

This is getting interesting,

can somebody explain why exactly this happens?

Answer

Kevin picture Kevin · Jan 28, 2009

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