我有一个应用程序,用户可以在其中玩很多类型的游戏。每场比赛延伸了Game
课程,其中有各种与游戏相关的内容。每个游戏还有一个相关的用户类别,它扩展了User
(包含电子邮件,用户名等),如ChessUser
和ScrabbleUser
,其中包含有关游戏的统计信息和其他用户信息。指定子类中的集合类型
在每个Game
类中,我需要一个当前正在玩游戏的所有用户的列表。因为所有的游戏都需要这个列表,我想把它放在User
类中,但是它包含了玩游戏的用户类型(ChessGame将包含一个ChessUsers列表),我不能在没有在检索时转换值宁可不做。有没有方法做到这一点,而无需投射检索值?
一些示例代码:
public class Game {
private List<Player> players;
public Player getPlayer(int index) {
return players.get(index);
}
}
public class Player {
private String username;
private String email;
}
public class ChessGame extends Game {
// getPlayer now needs to return a ChessPlayer, hopefully without casting
}
public class ChessPlayer extends Player {
private int checkmates;
}
您正在寻找的是[泛型](http://docs.oracle.com/javase/tutorial/java/generics/index.html)。 –
检查'getPlayer'。返回类型不是void,而是Player。 –