I have a class A which implements Comparable interface, and a class B which extends A. I need to find a way to overwrite compareTo
in class B.
I found a similar question Cannot use comparable with father-son-grandson inheritance And tried to implement offered solution
Class A:
public class A<E extends A> implements Comparable<E>{
String surname;
int age;
A(String surname, int age){
this.surname = surname;
this.age = age;
}
public int compareTo(E o) {
int res=0;
res =this.surname.compareTo(o.surname);
if(res==0)
res = this.age-o.age;
return res;
}
Class B:
public class B extends A<B> {
int num;
Student(String surname, int age, int num){
super(surname,age);
this.num = num;
}
@Override
public int compareTo(B o){
int res=0;
res =this.surname.compareTo(o.surname);
if(res==0)
res = this.age-o.age;
if(res ==0){
res= this.num-o.num;
}
return res;
}
Exception:
Exception in thread "main" java.lang.ClassCastException: class T4.A cannot be cast to class T4.B (T4.A and T4.B are in unnamed module of loader 'app')