在this问题的第二次尝试(初始密码是不够的,突出的问题)周期性仿制药(试行2)
这里是不编译代码:
interface Player<R, G extends Game>
{
R takeTurn(G game);
}
interface Game<P extends Player>
{
void play(P player);
}
abstract class AbstractGame<R, P extends Player>
implements Game<P>
{
public final void play(final P player)
{
final R value;
value = player.takeTurn(this);
turnTaken(value);
}
protected abstract void turnTaken(R value);
}
public class XPlayer
implements Player<Integer, XGame>
{
@Override
public Integer takeTurn(final XGame game)
{
return (42);
}
}
public class XGame<P extends Player<Integer, XGame>>
extends AbstractGame<Integer, XPlayer>
{
@Override
protected void turnTaken(final Integer value)
{
System.out.println("value = " + value);
}
}
public class Main
{
public static void main(final String[] argv)
{
final XPlayer player;
final XGame game;
player = new XPlayer();
game = new XGame();
game.play(player);
}
}
我是什么碰到的是试图让AbstractGame中的play方法编译。看起来我必须在游戏和玩家的圈子中加入泛型才能扩展/实现,但对于我来说,我无法得到它。
这个play方法在AbstractGame类中必须是最终的,并且没有办法进行转换,并且我不想编写像turnTaken之类的另一个方法来让它工作,如果我没有至。
编辑:这里要求的是,编译代码,但需要投:
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);
}
abstract class AbstractGame<R, G extends Game<R, G, P>, P extends Player<R, P, G>>
implements Game<R, G, P>
{
public final void play(final P player)
{
final R value;
value = player.takeTurn((G)this);
turnTaken(value);
}
protected abstract void turnTaken(R value);
}
class XPlayer
implements Player<Integer, XPlayer, XGame>
{
@Override
public Integer takeTurn(final XGame game)
{
return (42);
}
}
class XGame
extends AbstractGame<Integer, XGame, XPlayer>
{
@Override
protected void turnTaken(final Integer value)
{
System.out.println("value = " + value);
}
}
class Main
{
public static void main(final String[] argv)
{
final XPlayer player;
final XGame game;
player = new XPlayer();
game = new XGame();
game.play(player);
}
}
Ech,看起来你已经遇到了java通用地狱,就像我曾经一样。然后我放弃了泛型,转而使用接口。 – 2012-02-24 15:16:41
你会如何通过接口来做到这一点?我不介意地狱,当我可以弄明白的时候:-) – TofuBeer 2012-02-24 17:25:50
我的意思是,而不是泛型,我已经制作了需要实现的适当对象的接口,并且我的方法采用了这种接口...... – 2012-02-25 18:39:46