给出以下代码:
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抛出:
The interface Comparable cannot be implemented more than once with
different arguments: Comparable<Player> and Comparable<Goalkeeper>
我不是要与
Player
进行比较,而是与Goalkeeper
进行比较,并且仅与他进行比较。我究竟做错了什么 ?
最佳答案
就设计逻辑而言,您没有做错任何事情。但是,由于Java实现泛型的方式(通过类型擦除),Java的局限性使您无法使用不同的类型参数来实现相同的泛型接口(interface)。
在您的代码中,Goalkeeper
从Player
继承了Comparable <Player>
的实现,并尝试添加自己的Comparable <Goalkeeper>
。这是不允许的。
解决此限制的最简单方法是在Comparable <Player>
中覆盖Goalkeeper
,将传入的播放器转换为Goalkeeper
,然后将其与this
守门员进行比较。
编辑
public int compareTo (Player otherPlayer) {
Goalkeeper otherGoalkeeper = (Goalkeeper)otherPlayer;
Integer _missedGoals = new Integer(this.missedGoals);
return _missedGoals.compareTo(otherGoalkeeper.getMissedGoals());
}