gpt4 book ai didi

java - 我需要在子类中覆盖 CompareTo 方法

转载 作者:行者123 更新时间:2023-11-30 05:42:22 25 4
gpt4 key购买 nike

我有一个实现 Comparable 接口(interface)的类 A 和一个扩展 A 的类 B。我需要找到一种方法来覆盖类 B 中的 compareTo

我发现了类似的问题 Cannot use comparable with father-son-grandson inheritance并尝试实现提供的解决方案

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

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')

最佳答案

你能发布失败的代码吗?

我刚刚在自己的机器上尝试过,它似乎可以工作。我唯一可以重新创建错误的是使用以下代码:b.compareTo((B) a);这是行不通的,因为您无法将父类型转换为其子类型。

此外,我认为这只是一个复制错误,但您提供的代码中缺少括号,并且类 B 的构造函数与类名不匹配。

关于java - 我需要在子类中覆盖 CompareTo 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55423294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com