何时在下面的代码中调用super()

时间:2016-01-29 20:17:07

标签: java constructor

试图了解super()方法何时被调用。在下面的代码中,Child类有一个带有this()的无参数构造函数,因此编译器无法插入super()。然后如何调用父构造函数。

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();
}

}

输出:

In main method

In parent constructor

In child constructor with argument

In child constructor with no argument

3 个答案:

答案 0 :(得分:6)

以下是发生的事情:

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();
    }
}

答案 1 :(得分:1)

super()在任何构造函数的第一行之前隐式调用,除非它显式调用super()或重载本身,或者类是java.lang.Object.

答案 2 :(得分:0)

在回答之前,我想澄清一些我认为对这个问题很重要的事情:

  • 如果没有为类声明构造函数,Java编译器会在编译时构建默认构造函数。

  • 当我们有一个不调用其父构造函数的子类时。同样,Java构建了父项的默认构造函数,然后执行子类&#39;构造函数(因为当子项是instanciate firstable时,其父项被创建)。

所以在这种情况下:

1)执行public main方法。 2)新生儿的实例 2.1)&#39;构建子构造函数&#39;但是第一个Java编译器为其父编译器构建默认构造函数。 2.2)构建子(没有接收参数的那个) 3)使用默认构造函数(上一个constr)中的age参数执行第二个构造函数。

我希望这会有所帮助。

相关问题