混合泛型和原始类型是行不通的。如果需要这些接口互相引用,则它们还需要引用自己:
interface Player<R, P extends Player<R, P, G>, G extends Game<R, G, P>>{ R takeTurn(G game);}interface Game<R, G extends Game<R, G, P>, P extends Player<R, P, G>>{ void play(P player);}尽管这看起来很头疼,但我不确定您为什么需要它。
编辑:
我能够
AbstractGame根据以上内容实施您的操作:
abstract class AbstractGame<R, P extends Player<R, P, AbstractGame<R, P>>> implements Game<R, AbstractGame<R, P>, P>{ public final void play(final P player) { final R value; value = player.takeTurn(this); turnTaken(value); } protected abstract void turnTaken(R value);}但是我不能
XGame和和完全关闭电路
XPlayer:
public class XGame extends AbstractGame<Integer, XPlayer> //compile error on XPlayer{ protected void turnTaken(Integer value) { }}public class XPlayer implements Player<Integer, XPlayer, XGame> //compile error on XGame{ @Override public Integer takeTurn(final XGame game) { return (42); }}这个问题似乎是每个通用声明
XGame和
XPlayer需要对方是正确的。这是您的设计真正具有周期性的地方。如果编译器“假定”每一个都是正确的,那么理论上它将起作用。但事实并非如此。
编辑2:
这个怎么样:
interface Game<R, G extends Game<R, G>>{ void play(Player<R, G> player);}interface Player<R, G extends Game<R, G>>{ R takeTurn(G game);}abstract class AbstractGame<R, G extends AbstractGame<R, G>> implements Game<R, G>{ public final void play(final Player<R, G> player) { final R value; value = player.takeTurn(self()); turnTaken(value); } protected abstract G self(); protected abstract void turnTaken(R value);}public final class XGame extends AbstractGame<Integer, XGame>{ protected XGame self() { return this; } protected void turnTaken(Integer value) { }}public class XPlayer implements Player<Integer, XGame>{ @Override public Integer takeTurn(final XGame game) { return (42); }}这里的关键是声明一个抽象方法
self(),
AbstractGame该方法返回type的实例
G。扩展类必须使用自己的类型解析继承的类型参数,并实现
self()return
this。这仅适用于内部代码,因为扩展类很容易说谎,例如:
public class EvilGame extends AbstractGame<Integer, AnotherGame> { ... }


