I have a parent class in Java called Flight
. I have children classes: JetFlight
, NormalFlight
, etc. which inherit from Flight
.
I want all the children classes to implement compareTo
from the Comparable
interface. I want them to inherit from Flight
because I want to use polymorphism (for example, initiate a Flight
array and fill it with objects of JetFlight
, NormalFlight
, etc.).
This is my code for the parent class:
public abstract class Flight {
public abstract int compareTo(Object o);
}
and this is the code for one of the children classes:
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;
}
}
This code won't compile because of 2 errors:
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'
How do I go about the situation when I want to inherit from a class and at the same time use generics on the child class?
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: