How to use generics and inherit from parent class without causing name clash?

耗尽温柔 提交于 2019-12-07 19:16:30

Option 1: Since your comparison is based upon flight time, and as far as I know, the variable flightTime can be pushed up in the parent class as all flights will have this feature. Then implement your compareTo() method in parent class itself.

Option 2: in case you want to keep your current code the way it is:

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

You can parameterize the Comparable on a type T bounded by Flight:

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

If you use Generics, you will get rid of the problem.

You need to define

public abstract int compareTo(JetFlight o);

and also use

public class JetFlight extends Flight implements Comparable<? extends JetFlight>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!