Given the following code :
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
}
The problem is that Goalkeeper
won't complie.
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>
I'm not trying to compare with Player
, but with Goalkeeper
, and only with him.
What am I doing wrong ?
The problem is described in Angelika Langer's Generics FAQ #401:
(I highly recommend checking out the whole description of the problem: it's more interesting than what I've quoted.)
In order to work around this restriction, you can try the following:
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).
In your code,
Goalkeeper
inherits fromPlayer
its implementation ofComparable <Player>
, and tries to add aComparable <Goalkeeper>
of its own; this is not allowed.The simplest way to address this limitation is to override
Comparable <Player>
in theGoalkeeper
, cast the player passed in toGoalkeeper
, and compare it tothis
goalkeeper.Edit