java - 什么时候在下面的代码中调用 super()

标签 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

最佳答案

这是发生了什么:

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

关于java - 什么时候在下面的代码中调用 super(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35093289/

相关文章:

c++ - 带有模板参数的构造函数

java - 可执行 jar 中的 RESTfull Jersey 应用程序错误

Java - 第一次使用构造函数 - 作业

javascript - .push 在构造函数中不起作用

java - 使用反射实例化 protected 构造函数时出现 NoSuchMethodException

java - Guice 辅助注入(inject)多个构造函数总是调用默认构造函数

java - 变量名中的句点意味着什么?

java - 核心 Java 动态绑定(bind)

java - 如何从JVM源码中找到native方法?

java - 如何使用不同的标签解码 xml