gpt4 book ai didi

java - 子类的构造函数无法编译

转载 作者:行者123 更新时间:2023-12-01 07:32:26 25 4
gpt4 key购买 nike

我有一个名为 Person 的抽象类和一个扩展 Person 的子类,名为 Employee。当我尝试编译时,出现构造函数错误。如何在 Employee 类中编写构造函数以便编译?如果您需要有关此问题的更多信息,请告诉我。谢谢。

public abstract class Person {    //Person abstract class
public String firstName;
public String lastName;
public char gender;

public Person(String fname, String lname, char g) { //constructor
firstName = fname;
lastName = lname;
gender = g;
}
public abstract void setDefaults();
}

public class Employee extends Person { //Employee class that extends Person

public Employee() { //i thought super(); might solve the problem, but it didnt.
super();
}
public void setDefaults() {}
}

最佳答案

您忘记将参数传递给 super() 声明。您的抽象构造函数需要参数。 super() 中的参数需要与父构造函数相同。可以使用不带任何参数的 super() 的唯一方法是,如果您的父构造函数根本没有任何参数。

public abstract class Person {    //Person abstract class
public String firstName;
public String lastName;
public char gender;

public Person(String fname, String lname, char g) { //constructor
firstName = fname;
lastName = lname;
gender = g;
}
public abstract void setDefaults();
}

public class Employee extends Person { //Employee class that extends Person

public Employee(String fname, String lname, char g) { //i thought super(); might solve the problem, but it didnt.
super(fname, lname, g);
}
public void setDefaults() {}
}

关于java - 子类的构造函数无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16248150/

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