java - 我们是否必须从其子类中的类 Object 调用默认构造函数

标签 java object constructor

如果我在类中调用或不调用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)构造函数的隐式调用作为构造函数中的第一个语句。

JLS, Section 8.8.7状态:

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/

相关文章:

java - 使 Eclipse 将选定的文本括在括号中

javascript - OOJS 相对于函数式 JavaScript 编程的性能

PHP - 脚本试图执行方法或访问不完整对象的属性

c++ - 在类函数中访问 vector 的元素

Scala 构造函数、命名参数和隐式 Getter/Setter

java - 向 JPopupMenu 添加垂直滚动?

java - 使用 CXF 服务 (ssl .net) 时连接重置

javascript - 如何将构造函数和原型(prototype)属性结合起来

java - 卡夫卡 : what's the best way to dynamically determine the number of partitions in a topic from the consumer side?

c++ - 临时类对象