gpt4 book ai didi

java - 将调用哪个 super 构造函数?如果我不在子类中调用 super 构造函数,是否仍然会调用 super 构造函数?

转载 作者:行者123 更新时间:2023-12-02 04:07:24 30 4
gpt4 key购买 nike

public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
super(“faculty”);
}
}

class Employee extends Person {
private String name;
public Employee() {
name = “no name”;
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
name = s;
System.out.println(s);
}
}

class Person {
//What if there was a parameterized constructor here
// e.g. public Person(String s){
// ... code ...
// }
}

在上面的Java代码中,如果我将Person类留空,并在Faculty类的无参数构造函数中调用 super 构造函数,那么将调用Employee的构造函数。但是如果 Person 类中有一个参数化构造函数怎么办?将调用哪个 super 构造函数?员工一还是人员一?

如果我不在子类中调用 super 构造函数, super 构造函数是否仍然被调用?

最佳答案

如果您向 Person 添加参数化构造函数,则您的 Employee 类将无法编译,因为默认情况下,将不再隐含无参数构造函数,但是您的 Employee 构造函数需要调用它。

现在,如果您的 Person 类同时具有无参数和 String 参数化构造函数(具有相同的 Employee 实现),您的代码将编译,并且调用 Employee 的构造函数仍会首先调用 Person 的无参数构造函数。

关于java - 将调用哪个 super 构造函数?如果我不在子类中调用 super 构造函数,是否仍然会调用 super 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34136831/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com