Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples

October 30, 2015 Categories: Inheritance. No Comments on Constructors in Inheritance

In this article we will look at the sequence in which constructors in inheritance are executed i.e., is the base class constructor invoked first or the derived class constructor is invoked first.

Consider two classes participating in simple inheritance. Let A be the super class and B be the sub class. Now, which constructor is invoked first? Is it the constructor of B followed by the constructor of A or vice versa? The sequence in which the constructors are invoked is from super class to sub class i.e, first the constructor of class A is executed then constructor of class B is executed.

The sequence of constructor invocation does not change even when super keyword is used. Now let’s consider a few examples to understand how constructors in inheritance works.

 

Example 1:

In the above example, object for class A is created. Since A is the super class only it’s constructor is invoked and the output will be:

Class A’s constructor is invoked

Now let’s look at another example.

 

Example 2:

In the above example, we are creating object for the sub class B. Since B is a sub class, constructor of class A is invoked first and then constructor of class B is invoked. Output for above program is:

Class A’s constructor is invoked
Class B’s constructor is invoked

Now, let’s look at another example.

 

Example 3:

In the above we can see multi-level inheritance A <- B <- C. The object we are creating is for sub class C. So the sequence in which constructors are executed is constructor of class A followed by class B followed by class C. Output of the above program is:

Class A’s constructor is invoked
Class B’s constructor is invoked
Class C’s constructor is invoked

I think above examples are enough to explain constructors in inheritance. If you have any doubts comment below.

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up
Thank you for visiting startertutorials.com! If you like this website do share with your friends by clicking on the social icons available on the left hand side.

As the domain name is quite large to remember, use this short domain to visit this site. Short domain: stuts.me