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/