标签:not lang 扩展 运行 ret extend 父类 忽略 类的方法
首先构造两个类,Employee类和Manager,前者是父类,后者是子类
public class Employee implements Comparable<Employee> {
private String name;
private int age;
private double salary;
@Override
public int compareTo(Employee o) {
return Double.compare(this.salary,o.salary);
}
}
public class Manager extends Employee {
private double bonus;
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
}
观察上面看到Employee类实现了Comparable 接口,里面的compareTo(x,y) 方法,这个方法是比较两个数的大小,如果x<y,则返回-1,如果x=y,则返回0,如果x>y,则返回一个正数.
上面的代码看似没有问题,但是在继承的过程中有可能会出现问题(这里Manager类是故意没写实现compareTo方法的,忽略这个问题).这是因为Manager扩展了Employee,而Employee实现的是Comparable
public class Manager extends Employee {
private double bonus;
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
@Override
public int compareTo(Employee other) {
Manager otherManger = (Manager) other; //这样绝对不行
...
}
}
这不符合"反对称"的规则.如果x是一个Employee对象,y是一个Employee对象,调用x.compareTo(y)不会抛出异常,它只是将x和y都作为雇员进行比较,因为每一个经理也都是雇员,这是可以进行比较的,但是反过来,y.compareTo(x)将会抛出一个异常ClassCastException.这是因为不是所有的雇员都是经理,不能把所有员工当成经理进行比较.
@Test
public void testCompareTo(){
Employee employee = new Employee("张三", 23, 6598.12);
Manager manager = new Manager("李四",24,5648.32,1.2);
int i = employee.compareTo(manager);
System.out.println(i); //这样是可以运行的,结果是1,因为是把manager当成employee比较
}
@Test
public void testCompareTo(){
Employee employee = new Employee("张三", 23, 6598.12);
Manager manager = new Manager("李四",24,5648.32,1.2);
int i = manager.compareTo(employee);
System.out.println(i); //这样是不能运行的,因为Employee不能当成Manager处理 java.lang.ClassCastException: domain.Employee cannot be cast to domain.Manager
}
解决方法:可以在Manager中重写方法,直接调用父类的方法,进行比较
@Override
public int compareTo(Employee other) {
return super.compareTo(other);
}
标签:not lang 扩展 运行 ret extend 父类 忽略 类的方法
原文地址:https://www.cnblogs.com/liuzhidao/p/13720380.html