如果我在类中调用或不调用Object
的默认构造函数,有什么区别吗:
public class BankCustomer {
private Person owner;
public BankCustomer(Person owner) {
this.owner = owner;
}
}
或者
public class BankCustomer {
private Person owner;
public BankCustomer(Person owner) {
super();
this.owner = owner;
}
}
最佳答案
没有什么区别。如果您没有显式调用父类(super class)构造函数,那么 Java 将插入对默认父类(super class)构造函数的隐式调用作为构造函数中的第一个语句。
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.
就你的情况而言,这是完全没有必要的。虽然将 super();
保留在那里没有什么坏处,但我会删除它。
关于java - 我们是否必须从其子类中的类 Object 调用默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22670934/