试图了解何时调用 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/