子类中的Java构造函数错误

标签 java

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/

相关文章:

Java OOP 传递 'inner' 字段

java - 使用套接字将文件从客户端发送到服务器,但获取一些大小为零的文件

java - 如何实现线程的 FIFO 队列?

java - tomcat启动但无法从另一台电脑上收听

java - 向我的 Web 应用程序添加两因素身份验证

java - 尝试添加另一个列表时 List.addAll 抛出 UnsupportedOperationException

java - 将数据 POST 到数据库时出现错误 204

java正则表达式

java - 在 Java 中实现最佳匹配搜索

java - UTC 的 Joda DateTime getMillis() 不正确,而是返回本地毫秒