如何在同一行代码中正确使用instanceof和compareTo?

时间:2018-10-04 12:59:10

标签: java instanceof compareto

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());
}

我现在想做的是检查员工是否是教职员工或员工(其父级员工的孩子)的一部分,并正确实施compareTo来检查工资。

这是工资/薪水方式

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;
} 

在这一点上,我有点卡住。

两者之间的工资/薪金不同。员工获得的费率为*小时,而教师的固定工资为1500。

1 个答案:

答案 0 :(得分:1)

compareTo内遗漏了一些(可争论的或不可以争论的)设计方面,等等...,您只需要检查参数o是否是Employee的实例。究竟是Faculty还是Staff的实例并不重要,因为执行的方法salary将对应于它的特定类型(FacultyStaff)多亏了多态性

所以,它会变成这样:

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
}