我在名为'Department'的类中使用了复制构造函数和继承来调用来自'Teacher'类的信息,该类是'Person'的子类。创建set / get方法后,我得到了上面的错误。任何人都知道为什么会发生这种情况?
public class Department {
private String deptName;
private int numMajors;
private Teacher[] listTeachers; //inherits from Person class
private Student[] listStudents; //inherits from Person class
// First constructor for Department
public Department(String dn, int nm, Teacher[] listTeachers, Student[] listStudents) {
this.deptName = dn;
this.numMajors = nm;
this.listTeachers = new Teacher[listTeachers.length];
for (int i = 0; i < this.listTeachers.length; i++)
{
this.listTeachers[i] = new Teacher (listTeachers[i]);
}
//set method for Teachers Array
public void setListTeachers (Teacher[] other) {
this.listTeachers = new Teacher[other.length];
for (int i = 0; i < listTeachers.length; i++) {
this.listTeachers[i] = new Teacher (other[i]);
}
}
//get method for Teachers Array
public Teacher[] getListTeachers() {
Teacher[] copyTeachers = new Teacher[listTeachers.length];
for (int i = 0; i < copyTeachers.length; i++) {
copyTeachers[i] = new Teacher(this.listTeachers[i]);
}
return copyTeachers;
}
以下是给我错误的行:
1)this.listTeachers[i] = new Teacher (listTeachers[i]);
2)this.listTeachers[i] = new Teacher (other[i]);
3)copyTeachers[i] = new Teacher(this.listTeachers[i]);
public class Teacher extends Person {
private String id;
private int salary;
private int num_yr_prof;
//Constructor for use in Teacher main method.
public Teacher(String n, int a, String s, boolean al, String i, int sal, int numyr) {
super(n, a, s, al);
this.id = i;
this.salary = sal;
this.num_yr_prof = numyr;
}
//Copy constructor for use in Department class.
public Teacher (String n, int a, String s, boolean al, Teacher other) {
super(n, a, s, al);
if (other == null) {
System.out.println("Fatal Error!");
System.exit(0);
}
this.id = other.id;
this.salary = other.salary;
this.num_yr_prof = other.num_yr_prof;
}
您的复制构造函数可能如下所示:
public Teacher(Teacher teacher) {
this( teacher.n, teacher.a, teacher.s, teacher.al,
teacher.id, teacher.salary, teacher.num_yr_prof );
}
由于您没有显示Person类的代码,因此我在这里使用了变量名n,a,s和al。它们应该替换为Person类中命名的那些变量。当然,这假设这些变量是公共的或受保护的。如果它们是私有的,则需要对这些变量使用getter(即使它们是公共的或受保护的,也是首选的)。
你需要给你的Teacher类一个接受教师的构造函数:
public Teacher(Teacher teacher) {
// do something
}