gpt4 book ai didi

子类中的Java构造函数错误

转载 作者:行者123 更新时间:2023-11-29 05:09:21 25 4
gpt4 key购买 nike

class Person 
{
String name = "No name";

public Person(String nm)
{
name = nm;
}
}
class Employee1 extends Person
{
String empID ="0000";
public Employee1(String id)
{ // Line 1
empID = id;
}
}
public class EmployeeTest
{
public static void main(String[] args) {
Employee1 e = new Employee1("4321");
Person p = new Person("Hello");
System.out.println(e.empID);
}
}

我得到编译错误说 constructor Person in class Person cannot be applied to given types; required String found no arguments 但是当我在 main 方法中创建新对象时,我正在为父类和子类传递参数。无法弄清楚为什么编译错误?

最佳答案

您需要正确地创建父类,将名称作为Person 构造函数的要求传递给它:

public Employee1(String id) {
super("person name"); // create the parent
empID = id;
}

或者可能是这样的:

public Employee1(String id, String name) {
super(name); // create the parent
empID = id;
}

public static void main(String[] args) {
Employee1 e = new Employee1("4321", "Hello");
// ...
}

关于子类中的Java构造函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29233574/

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