如何使用泛型并从父类继承而不导致名称冲突? [英] How to use generics and inherit from parent class without causing name clash?
问题描述
我在 Java 中有一个名为 Flight
的父类.我有子类:JetFlight
、NormalFlight
等,它们继承自 Flight
.
I have a parent class in Java called Flight
. I have children classes: JetFlight
, NormalFlight
, etc. which inherit from Flight
.
我希望所有子类都从 Comparable
接口实现 compareTo
.我希望它们继承自 Flight
因为我想使用多态性(例如,启动一个 Flight
数组并用 JetFlight
的对象填充它,NormalFlight
等).
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.).
这是我的父类代码:
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;
}
}
由于 2 个错误,此代码无法编译:
This code won't compile because of 2 errors:
1) 'java.lang.Comparable' 中的compareTo(T) 与'Flight' 中的'compareTo(Object)' 冲突;两个对象具有相同的擦除,但都不覆盖另一个.
2) 类 'JetFlight' 必须声明为抽象或在 'Flight' 中实现抽象方法 'compareTo(Object)'
如果我想继承一个类,同时在子类上使用泛型,我该如何处理?
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:由于您的比较基于飞行时间,据我所知,变量飞行时间
可以在父类中向上推,因为所有航班都将具有此功能.然后在父类中实现你的 compareTo() 方法.
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.
选项 2:如果您想保持当前代码不变:
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;
}
这篇关于如何使用泛型并从父类继承而不导致名称冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!