14

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 ?

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
JAN
  • 21,236
  • 66
  • 181
  • 318

3 Answers3

17

The problem is described in Angelika Langer's 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.

(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:

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());
    }
    // ...
}
Community
  • 1
  • 1
alf
  • 8,377
  • 24
  • 45
7

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 from Player its implementation of Comparable <Player>, and tries to add a Comparable <Goalkeeper> of its own; this is not allowed.

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.

Edit

public int compareTo (Player otherPlayer) {
    Goalkeeper otherGoalkeeper = (Goalkeeper)otherPlayer;
    Integer _missedGoals = new Integer(this.missedGoals);
    return _missedGoals.compareTo(otherGoalkeeper.getMissedGoals());
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • You mean to do this : "public class Goalkeeper extends Player implements Comparable " ... public int compareTo (Goalkeeper otherGoalkeeper) { Integer _missedGoals = new Integer(this.missedGoals); return _missedGoals.compareTo(otherGoalkeeper.getMissedGoals()); }" ?? – JAN Jan 01 '12 at 20:28
  • 2
    @ron You do not even have to do `implements Comparable `: it's there because you extend `Player`. Just do this: `@Override public int compareTo(Player otherGoalkeeper) {...}` – Sergey Kalinichenko Jan 01 '12 at 20:31
  • That's the problem : please notice that class Player doesn't have the field missedGoals ,and class Goalkepper does. I did this : public int compareTo (Goalkeeper otherGoalkeeper) { Integer _missedGoals = new Integer(this.missedGoals); return _missedGoals.compareTo(otherGoalkeeper.getMissedGoals()); } – JAN Jan 01 '12 at 20:57
  • 3
    @ron problem is, that violates [Liskov's substitution principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle): if you claim that `Goalkeeper` *is-a* `Player`, it must be able to do whatever `Player` can do—including being compared with any `Player`. – alf Jan 01 '12 at 23:23
  • 1
    @ron Since `Goalkeeper` is a `Player`, you should be able to cast `Player` to `Goalkeeper` inside the `compareTo` method. I added a code snippet to the answer to illustrate this point. – Sergey Kalinichenko Jan 02 '12 at 01:10
  • @alf , I now understand what the problem was , I didn't think that if A inherit from B , then what A is being compared to must also include B to do the same ... great, thank you all ! I've learned a lot from you guys. – JAN Jan 02 '12 at 04:51
  • Be careful that "otherPlayer" might not be a "Goalkeeper" but a "Player". As so, you might not be able to call getMissedGoals(). To do that, you should use instanceof and check whether "otherPlayer" is or is not a "GoalKeeper". – jfajunior Oct 09 '18 at 14:27
0

I would like to add two points to the existing good answers.

  1. There are reasons why you might not want the design you tried even if it had been possible. It is a bit fluffy.
  2. There are other possible solutions in addition to the one that Sergey Kalinichenko presents.

Your design has downsides

As you know, your design isn’t possible with Java. It’s a restriction with Java generics. Let’s for a moment play what if it had been possible. It would imply some behaviour that I think many would find surprising and/or confusing.

With you design, assume we have:

    Goalkeeper goalkeeper1 = new Goalkeeper("Imene");
    Goalkeeper goalkeeper2 = new Goalkeeper("Sofia");
    Player goalkeeper3 = new Goalkeeper("Maryam");

    goalkeeper1.compareTo(goalkeeper2); // would call Goalkeeper.compareTo(Goalkeeper)
    goalkeeper1.compareTo(goalkeeper3); // would call Player.compareTo(Player)

We can take it one step further:

    List<? extends Player> list1 = new ArrayList<Goalkeeper>();
    List<? extends Player> list2 = new ArrayList<Player>();

Now we fill both lists with goalkeepers (only) and sort them. Now list1 should be sorted using Goalkeeper.compsreTo() and list2 probably using Player.compareTo(). It’s beginning to be confusing, isn’t it? Would you want such a design? Would you prefer one where you are more explicit about which way to compare is used when? (Yes, I know, you cannot fill the lists through the variables list1 and list2. You would have to fill the lists before assigning them to those two variables.)

A couple of solutions

Solution 1: Instead of one of your compareTo methods (or both of them) use a Comparator. Either a Comparator<Player> or a Comparator<Goalkeeper> or one of each. For example:

    Comparator<Player> playerComparator = Comparator.comparingInt(Player::getScoredGoals);

Solution 2: Introduce a separate class for players that are not goalkeepers. I am calling it FieldPlayer for now for lack of a better word. Both FieldPlayer and Goalkeeper should be subclasses of Player. FieldPlayer implements Comparable<FieldPlayer> and Goalkeeper already implements Comparable<Goalkeeper>. Now Player doesn’t need to implement Comparable, and the conflict is avoided.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161