【发布时间】:2012-02-23 23:21:39
【问题描述】:
第二次尝试this 问题(最初的代码不足以突出问题)
这里是没有编译的代码:
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 类中必须是 final 的,并且没有办法进行强制转换,如果我不需要的话,我不想写像 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 通用地狱,就像我曾经一样。然后我放弃了泛型,转而使用接口。
-
如何通过接口实现?我不介意,当我能弄明白的时候:-)
-
我的意思是,我没有使用泛型,而是创建了需要实现适当对象的接口,并且我的方法采用了这些接口...
-
嗯...对我的问题没有任何帮助。