Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when is super() called in the below code

Trying to understand when does the super() method called. In the below code, Child class has a no-argument-constructor with this(), so compiler cannot insert super(). Then how is parent constructor called.

public class Parent
{
    public Parent()
    {
        System.out.println("In parent constructor");
    }
 }


public class Child extends Parent
{
private int age;

public Child()
{   
    this(10);
    System.out.println("In child constructor with no argument");
}

public Child(int age)
{
    this.age = age;
    System.out.println("In child constructor with argument");
}

public static void main(String[] args)
{
    System.out.println("In main method");
    Child child = new Child();
}

}

Output :

In main method

In parent constructor

In child constructor with argument

In child constructor with no argument
like image 476
puvi Avatar asked Mar 14 '23 11:03

puvi


2 Answers

Here is what happens:

public class Parent
{
    public Parent()
    {
        System.out.println("In parent constructor"); // 4 <------
    }
}


public class Child extends Parent
{
    private int age;

    public Child()
    {
        this(10); // 2 <------
        System.out.println("In child constructor with no argument"); // 6 <------
    }

    public Child(int age)
    {
        // 3 -- implicit call to super()  <------
        this.age = age;
        System.out.println("In child constructor with argument"); // 5 <------
    }

    public static void main(String[] args)
    {
        System.out.println("In main method"); // 1 <------
        Child child = new Child();
    }
}
like image 129
Mohammed Aouf Zouag Avatar answered Mar 31 '23 07:03

Mohammed Aouf Zouag


super() is called implicitly before the first line of any constructor, unless it explicitly calls super() or an overload itself, or the class is java.lang.Object.

like image 22
user207421 Avatar answered Mar 31 '23 07:03

user207421