Java Constructors: Using super()

Java Constructors: Using super()


The magic of super()

We have seen earlier, the usage of this() statement where it is used to call in between the constructors belonging to the same class. Here no inheritance is involved. Now in this posting, let us learn how to call a super class constructor from subclass constructor.

Example on super()

super()

super("Bushy Animal");

super() statement is used to call super class constructor from subclass constructor. One object of l1 is created in main() method calling IV constructor. super("Bushy Animal") written in IV with string parameter calls super class matching constructor; it is obviously II. Instead of super("Bushy Animal"), if just super() is written, the IV will call I (ofcourse, it is the default behaviour also).

Using both this() and super() in one program.

Now let us call all the 4 constructors, 2 from super class and 2 from subclass with one subclass object creation. Just modify the previous code.

Before going into the code know this() Vs super(), just remember this() calls same class constructor and super() calls super class constructor.

Example on this() and super() usage

super()

In the main(), IV constructor is called. in IV, this() is written which calls the III of the same class. In III, super("Bushy Animal") is written which calls matching super class constructor II with string parameter. In II, this() is written which calls same class matching constructor I (that without parameter).

The order of calling is IV, III, II and I. The output will be in reverse order.

One thought on “Java Constructors: Using super()

  1. Jena Wiltrout

    This website is completely awesome. I’ve ask these stuffs a long time and
    I realised that is professional, fast to comprehend. I congratulate you for this article that I’ll tell to prospects around.

    I request you to visit the gpa-calculator.co site where each college student
    or scholar can find ratings grade point average rating.
    Be great!

Leave a Reply

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