给定以下代码:
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 进行比较,而且只与他进行比较。
我做错了什么?
最佳答案
该问题在 Angelika Langer 的 Generics FAQ #401 中有所描述。 :
Can a class implement different instantiations of the same generic interface?
No, a type must not directly or indirectly derive from two different instantiations of the same generic interface.
The reason for this restriction is the translation by type erasure. After type erasure the different instantiations of the same generic interface collapse to the same raw type. At runtime there is no distinction between the different instantiations any longer.
(我强烈建议查看问题的完整描述:它比我引用的内容更有趣。)
为了解决此限制,您可以尝试以下操作:
public class Player<E extends Player> extends Participant implements Comparable<E> {
// ...
public int compareTo(E otherPlayer) {
Integer _scoredGoals = this.scoredGoals;
return _scoredGoals.compareTo(otherPlayer.getPlayerGoals());
}
// ...
}
public class Goalkeeper extends Player<Goalkeeper> {
// ...
@Override
public int compareTo(Goalkeeper otherGoalkeeper) {
Integer _missedGoals = this.missedGoals;
return _missedGoals.compareTo(otherGoalkeeper.getMissedGoals());
}
// ...
}
关于java - 不能使用 comparable with father-son-grandson inheritance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8694848/