(true 或 false)如果您编写的构造函数的第一个语句不是对另一个构造函数的调用,则插入默认构造函数调用。
这个问题的答案是正确的。 然后我尝试创建了一些链式构造函数。
public class Temp {
// default constructor 1
Temp()
{
System.out.println("default");
}
// parameterized constructor 2
Temp(int x)
{
System.out.println(x);
}
public static void main(String args[])
{
new Temp(8);
}
}
输出:
8
未打印“默认”。所以我认为默认构造函数没有被调用。答案应该是假的。有人能解释一下为什么吗?
最佳答案
If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.
所以a default constructor call in inserted.
,但它是您的父类(super class)的默认构造函数(在本例中: Object
)而不是您声明的类。
关于java - 默认构造函数链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51412715/