当前位置: 代码迷 >> Eclipse >> 超类、子类接口实现,泛型数组排序综合使用遇到的有关问题
  详细解决方案

超类、子类接口实现,泛型数组排序综合使用遇到的有关问题

热度:9462   发布时间:2013-02-25 21:52:31.0
超类、子类接口实现,泛型数组排序综合使用遇到的问题
我实现了几个类:
Person、Employee extends Person、Student extens Person、Manager extends Employee
在书上看到,实现接口的方法:
1、将类声明为实现给定的接口;
2、对接口中的所有方法进行定义。
我在声明的时候(Class Person implements comparable)
报错:The type Person must implement the inherited abstract method Comparable.compareTo(Object),于是我认为无需声明,所以去掉了声明的部分。

在Person类中定义接口的compareTo方法:
public int compareTo(Person other){
return getBirthday().compareTo(other.getBirthday());
}

//Birthday是Persn类中的一个Date类型私有数据,getBirthday()是访问器函数

我认为子类会继承超类中的除构造器方法以外的所有方法和域,所以我没有在子类中定义compareTo方法

然后我再主函数中搞了一个泛型数组,然后填入了2个Employee对象、1个Manager对象、1个Student对象,然后toString到一个普通Person[]数组中,之后用Arrays.sort排序,在排序的过程中就报错:
Exception in thread "main" java.lang.ClassCastException: com.employee.Employee cannot be cast to java.lang.Comparable
看到报错后,我又在Employee中定义了compareTo方法,还是不行,我实在是不明白这是为什么。

请高手指教
引用:
2、对接口中的所有方法进行定义。
我在声明的时候(Class Person implements comparable)
报错:The type Person must implement the inherited abstract method Comparable.compareTo(Object),于是我认为无需声明,所以去掉了声明的部分。
报错……


必须声明,如果person类不想实现这个方法,直接把Persion类定义成Abstract就行了
  相关解决方案