我正在创建一个名为“Employee”的用户定义类,它将保存有关员工的基本数据。例如姓名、生日和入职日期。
在我之前的程序中,我创建了一个名为“Date”的用户定义类,它包含 3 个 int 值(月、日、年)。
Employee类的生日和入职日期必须是Date类型。
这是我的 Date 类的构造函数 //日、月、年之前初始化过
public Date(int m, int d, int y){
day = d;
month = m;
year = y;
}
以及实例化 Date 对象的例子
Date date1 = new Date(1, 1, 1582);
这是我的 Employee 类的构造函数
public Employee(String fName, String lName, Date d1, Date d2) {
firstName = fName;
lastName = lName;
date1 = d1;
date2 = d2;
}
当试图创建 Employee 类的对象时(在另一个类中,这个类被命名为“Employee Test”)我得到一个错误
"required:String, String, Date,Date
found: String, String, int, int, int, int, int, int".
Employee e = new Employee("Tom" , "Doe",1 , 5 , 1995, 1 , 6 , 2011 );
问题似乎是对象正在接收作为 int 值而不是类型 Date 的数据,即使 Date 对象本身需要 3 个 int 值。
我对如何创建这个对象感到困惑,是我的构造函数错了吗?在创建 Employee 对象时,我是否需要将实际实例化的对象作为参数传递?
谢谢
最佳答案
您需要传递一个日期对象!看看这个示例:
Date date1 = new Date(1, 5, 1995);
Date date1 = new Date(1, 6, 2011);
Employee e = new Employee("Tom" , "Doe",date1, date2 );
现在您将 Date 对象的两个引用传递给 Employee 构造函数。你甚至可以这样做:
Employee e = new Employee("Tom" , "Doe", new Date(1, 5, 1995), new Date(1, 6, 2011));
关于java - 如何使用另一个类的参数创建一个类的对象? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40580589/