无法将可比对象与父子孙子继承 [英] Cannot use comparable with father-son-grandson inheritance
问题描述
给出以下代码:
public abstract class Participant {
private String fullName;
public Participant(String newFullName) {
this.fullName = new String(newFullName);
}
// some more code
}
public class Player extends Participant implements Comparable <Player> {
private int scoredGoals;
public Player(String newFullName, int scored) {
super(newFullName);
this.scoredGoals = scored;
}
public int compareTo (Player otherPlayer) {
Integer _scoredGoals = new Integer(this.scoredGoals);
return _scoredGoals.compareTo(otherPlayer.getPlayerGoals());
}
// more irrelevant code
}
public class Goalkeeper extends Player implements Comparable <Goalkeeper> {
private int missedGoals;
public Goalkeeper(String newFullName) {
super(newFullName,0);
missedGoals = 0;
}
public int compareTo (Goalkeeper otherGoalkeeper) {
Integer _missedGoals = new Integer(this.missedGoals);
return _missedGoals.compareTo(otherGoalkeeper.getMissedGoals());
}
// more code
}
问题是 Goalkeeper
无法编译。
当我尝试编译该代码时,Eclipse会抛出:
When I try to compile that code the Eclipse throws:
The interface Comparable cannot be implemented more than once with
different arguments: Comparable<Player> and Comparable<Goalkeeper>
我不想与 Player
,但只有 Goalkeeper
,并且只有他。
I'm not trying to compare with Player
, but with Goalkeeper
, and only with him.
我在做什么错?
推荐答案
就设计逻辑而言,您没有做错任何事情。但是,Java有一个限制,它会阻止您使用不同的类型参数实现相同的泛型接口,这是由于Java实现泛型的方式(通过类型擦除)。
As far as the logic of your design goes, you are not doing anything wrong. However, Java has a limitation that prevents you from implementing the same generic interface with different type parameters, which is due to the way it implements generics (through type erasure).
在您的代码中, Goalkeeper
从 Player
继承其 Comparable< Player> 的实现。 code>,并尝试添加自己的
可比较的< Goalkeeper>
;
In your code, Goalkeeper
inherits from Player
its implementation of Comparable <Player>
, and tries to add a Comparable <Goalkeeper>
of its own; this is not allowed.
解决此局限性的最简单方法是在可疑对象中覆盖 Comparable< Player>
守门员
,将传入的玩家投射到守门员
,并将其与此$进行比较c $ c>守门员。
The simplest way to address this limitation is to override Comparable <Player>
in the Goalkeeper
, cast the player passed in to Goalkeeper
, and compare it to this
goalkeeper.
编辑
public int compareTo (Player otherPlayer) {
Goalkeeper otherGoalkeeper = (Goalkeeper)otherPlayer;
Integer _missedGoals = new Integer(this.missedGoals);
return _missedGoals.compareTo(otherGoalkeeper.getMissedGoals());
}
这篇关于无法将可比对象与父子孙子继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!