java - 在构造函数中调用 super()

标签 java constructor

我刚刚使用了 Eclipse 的“使用字段生成构造函数”功能,它为我提供了以下构造函数:

public Credentials(String userName, String password) {
    super();
    this.userName = userName;
    this.password = password;
}

Credentials 类没有显式扩展另一个类,因此我猜它扩展了 Objectsuper(); 调用有何用处?

最佳答案

如果您将构造函数定义为:

public Credentials(String userName, String password) {
    this.userName = userName;
    this.password = password;
}

然后编译器无论如何都会添加对父类(super class)构造函数的隐式调用,因此这不会对编译后的代码产生任何差异。

The Credentials class does not explicitly extend another class so it extends Object I guess. What is the super(); call good for?

但是您的类隐式扩展了 Object,因此将调用 Object()

关于java - 在构造函数中调用 super(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22374323/

相关文章:

Java登录不读取加密密码

java - Maven Clean 因签名异常而失败

java - 如何检查int是否为null

java - 代码无法显示图像 - Image.createImage 处的 java.io.IOException

c++ - 覆盖另一种方法使用的父类(super class)回调函数[C++]

C++构造函数中父类(super class)的init成员

c++ - 构造函数初始化列表。初始化顺序

预先完成一些工作的 C++ 委托(delegate)构造函数

Java 返回值(在 try/catch 子句中)

c# - 在不存在的结构布局中循环