Cannot use comparable with father-son-grandson inheritance

前端 未结 2 558
我寻月下人不归
我寻月下人不归 2021-02-13 21:50

Given the following code :

public abstract class Participant {
    private String fullName;

    public Participant(String newFullName) {
        this.fullName          


        
相关标签:
2条回答
  • 2021-02-13 21:56

    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());
        }
        // ...
    }
    
    0 讨论(0)
  • 2021-02-13 22:05

    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());
    }
    
    0 讨论(0)
提交回复
热议问题