问题
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?
回答1:
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;
}
回答2:
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;
}
}
回答3:
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>
来源:https://stackoverflow.com/questions/46021716/how-to-use-generics-and-inherit-from-parent-class-without-causing-name-clash