我在Java中有一个父母类,称为Flight
。我有孩子课程:JetFlight
,NormalFlight
等。从Flight
继承。
我希望所有儿童课程都可以从Comparable
接口实现compareTo
。我希望它们从Flight
继承,因为我想使用多态性(例如,启动Flight
数组,并用JetFlight
,NormalFlight
等的对象填充它)。
这是我的父级代码:
public abstract class Flight {
public abstract int compareTo(Object o);
}
这是一个儿童课之一的代码:
public class JetFlight extends Flight implements Comparable<JetFlight> {
private int flightTime;
public JetFlight(int flightTime) {
this.flightTime = flightTime;
}
public int compareTo(JetFlight j) {
return this.flightTime - j.flightTime;
}
}
由于2个错误,此代码不会编译:
1)compareTo(T) in 'java.lang.Comparable' clashes with 'compareTo(Object)' in 'Flight'; both objects have the same erasure, yet neither overrides the other.
2)Class 'JetFlight' must either be declared abstract or implement abstract method 'compareTo(Object)' in 'Flight'
当我想从班级继承并同时使用子班上的仿制药时,我该如何处理这种情况?
选项1:由于您的比较是基于飞行时间,据我所知,变量 flightTime
可以在父班上推上,因为所有航班都具有此功能。然后在父类本身中实现compareTo()方法。
选项2:如果您想以:
保持当前代码 public abstract class Flight implements Comparable<Flight> {
public abstract int compareTo(Flight o);
}
public class JetFlight extends Flight {
private int flightTime;
public JetFlight(int flightTime) {
this.flightTime = flightTime;
}
public int compareTo(Flight f) {
if(!(f instanceof JetFlight)){
throw new IllegalArgumentException();
}
return this.flightTime - ((JetFlight)f).flightTime;
}
您可以在T
上的类型CC_15上参数化Comparable
:
abstract class Flight<T extends Flight<T>> implements Comparable<T> {
public abstract int compareTo(T o);
}
class JetFlight extends Flight<JetFlight> {
private int flightTime;
public JetFlight(int flightTime) {
this.flightTime = flightTime;
}
public int compareTo(JetFlight j) {
return this.flightTime - j.flightTime;
}
}
如果您使用仿制药,则会摆脱问题。
您需要定义
public abstract int compareTo(JetFlight o);
也使用
public class JetFlight extends Flight implements Comparable<? extends JetFlight>