如何在同一行代码中正确使用 instanceof 和 compareTo?
How to properly use instanceof and compareTo in the same line of code?
public int compareTo(Object o) {
Employee emp;
if (o instanceof Faculty) { //if it is faculty
emp = (Faculty)o; //cast this employee to an object
} else if (o instanceof Staff) { // if it is staff
emp = (Staff)o; //cast this employee to an object
}
int difference = this.salary().compareTo(emp.salary());
}
我现在要做的是检查员工是否属于教职员工(children 的 parent class 员工)并正确实施compareTo 查看工资。
这是pay/salary方法
public Faculty(String n, String i, String o, double s) {
super(n, i, o); //add a o which is office from its parent Employee
salary = s;
}
public double pay() {
return salary;
}
我有点卡在这一点上了。
两者的pay/salary不同。员工按费率 * 小时数获得报酬,教师获得固定工资 1500。
省略一些(有争议的或没有的)设计方面等...在 compareTo
中,您只需要检查参数 o
是否是 Employee
的实例。它是 Faculty
还是 Staff
的特定实例并不重要,因为执行的方法 salary
将对应于它的特定类型(Faculty
或 Staff
)感谢多态性。
所以,它会是这样的:
public int compareTo(Object o) {
return o instanceof Employee ? this.salary().compareTo(((Employee)o).salary()) : -1;
// replace -1 for any value you'd like to return if o is not instance of Employee
}
public int compareTo(Object o) {
Employee emp;
if (o instanceof Faculty) { //if it is faculty
emp = (Faculty)o; //cast this employee to an object
} else if (o instanceof Staff) { // if it is staff
emp = (Staff)o; //cast this employee to an object
}
int difference = this.salary().compareTo(emp.salary());
}
我现在要做的是检查员工是否属于教职员工(children 的 parent class 员工)并正确实施compareTo 查看工资。
这是pay/salary方法
public Faculty(String n, String i, String o, double s) {
super(n, i, o); //add a o which is office from its parent Employee
salary = s;
}
public double pay() {
return salary;
}
我有点卡在这一点上了。
两者的pay/salary不同。员工按费率 * 小时数获得报酬,教师获得固定工资 1500。
省略一些(有争议的或没有的)设计方面等...在 compareTo
中,您只需要检查参数 o
是否是 Employee
的实例。它是 Faculty
还是 Staff
的特定实例并不重要,因为执行的方法 salary
将对应于它的特定类型(Faculty
或 Staff
)感谢多态性。
所以,它会是这样的:
public int compareTo(Object o) {
return o instanceof Employee ? this.salary().compareTo(((Employee)o).salary()) : -1;
// replace -1 for any value you'd like to return if o is not instance of Employee
}