use*_*210 5 java extends interface compareto comparable
我一直在尝试以这种方式覆盖compareTo:这是原始的:
@Override
public int compareTo(ProductPart6 s)
{
return this.getproductName().compareTo(s.getproductName());
}
Run Code Online (Sandbox Code Playgroud)
这就是我试图重写它的方法:它抛出一个错误 SubClass 类型的方法compareTo(SubClass) 必须重写或实现超类型方法。
@Override
public int compareTo(SubClass s)
{
return this.getTitle().compareTo(s.getTitle());
}
Run Code Online (Sandbox Code Playgroud)
我认为这是非常错误的。我的 ProductPart6 没有 getTitle() ,这会导致它
@Override
public int compareTo(ProductPart6 s)
{
return this.getTitle().compareTo(s.getTitle());
}
Run Code Online (Sandbox Code Playgroud)
抛出错误(ProductPart6 类型的 getTitle() 未定义) - 如果我在那里定义了它,则没有必要覆盖它。我究竟做错了什么?我有扩展 ProductPart6 的子类,并且 ProductPart6 实现了 Comparable - 我以为我可以在子类上实现它,但没有。那是不行的。
当类实现时,Comparable<T>您必须指定T可以与类实例进行比较的对象 () 类型。的所有子实现compareTo还必须接受相同类型的参数T。
让我们考虑两个类:
public class Alpha implements Comparable<Alpha> {
@Override
public int compareTo(Alpha a) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
和...
public class Bravo extends Alpha {...}
Run Code Online (Sandbox Code Playgroud)
如果您尝试重写,compareTo则Bravo必须提供类型参数Alpha,因为Alpha该类型满足T类声明(包含在implements Comparable其中)。否则,它不会重写超类型方法,因此编译器会抱怨注释@Override,这就是您在这里看到的。
就您而言,我认为您需要考虑 和 是否ProductPart6足够SubClass兼容以这种方式使用。如果不是,请考虑使用单独的Comparator实例,或者重构以创建满足T这两种情况的通用类型。