When super () is called in the code below

Trying to figure out when the super () method is being called. In the code below, the child class has a no-argument constructor with this (), so the compiler cannot insert super (). Then how the parent constructor is 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();
}

}

Exit:

In main method

In parent constructor

In child constructor with argument

In child constructor with no argument
+4
source share
3 answers

Here's 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();
    }
}
+6
source

super()called implicitly before the first line of any constructor, unless it explicitly calls super()either the overload itself or the classjava.lang.Object.

+1
source

, :

  • , Java .

  • , . , Java , (, , ).

, :

1) . 2) 2.1) "Build child constructor", Java . 2.2) (, ) 3) ( constr).

, .

0

Source: https://habr.com/ru/post/1626582/


All Articles