如何使用仿制药并从父类中继承而不会引起名称冲突



我在Java中有一个父母类,称为Flight。我有孩子课程:JetFlightNormalFlight等。从Flight继承。

我希望所有儿童课程都可以从Comparable接口实现compareTo。我希望它们从Flight继承,因为我想使用多态性(例如,启动Flight数组,并用JetFlightNormalFlight等的对象填充它)。

这是我的父级代码:

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>

相关内容

  • 没有找到相关文章

最新更新