gpt4 book ai didi

java - 不能使用 comparable with father-son-grandson inheritance

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:51:40 25 4
gpt4 key购买 nike

给定以下代码:

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 genericinterface?

No, a type must not directly or indirectly derive fromtwo different instantiations of the same generic interface.

The reasonfor this restriction is the translation by type erasure. After typeerasure the different instantiations of the same generic interfacecollapse to the same raw type. At runtime there is no distinctionbetween 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com