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
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();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With