【发布时间】:2014-01-21 07:32:27
【问题描述】:
大多数泛型和通配符的示例都涉及集合,但我正在尝试学习如何仅将它们与类一起使用。我想学习这种更现代的泛型方法,这样我就可以避免子类覆盖超类中的方法时出现的尴尬强制转换。
我有一个猜谜游戏的抽象类,它可能用于猜数字游戏、猜词游戏,甚至是 Mastermind。游戏包中包含 Level 和 Score 的抽象类。然后我想对猜谜游戏进行子类化,并将级别和分数子类化以制作特定游戏。
这是 Score 的抽象类:
// a score is a measure of how close a guess is to being correct
public abstract class Score{
public abstract boolean equals(Class<? extends Score> otherScore);
public abstract boolean isWin(Class<? extends Level> level);
}
在为 isWin 编写参数时,我想说的是:期望得到一个 Level 或 Level 子类的参数。
然后我创建了我的 Score for Mastermind 的子类:
public class MastermindScore extends games.Score{
int numRightPlace;
int numWrongPlace;
public MastermindScore(int numRightPlace, int numWrongPlace){
this.numRightPlace = numRightPlace;
this.numWrongPlace = numWrongPlace;
}
public boolean equals(MastermindScore otherScore){
if (this.numRightPlace==otherScore.numRightPlace){
if (this.numWrongPlace == otherScore.numWrongPlace){
return true;
}
}
return false;
}
public boolean isWin(MastermindLevel level){
return this.numRightPlace == level.numSlots;
}
这不会编译,因为它认为我没有正确覆盖抽象超类所需的方法。因此,即使子类的 isWin 方法有一个参数是 Level 的子类,它也不会将其识别为预期的类型。
然后我将 Level 子类的类声明行更改为如下所示:
public class MastermindLevel<T extends games.Level>{
public final int numColors;
public final int numSlots;
public MastermindLevel(int numColors, int numSlots, int maxGuesses){
super(maxGuesses);
this.numColors = numColors;
this.numSlots = numSlots;
}
}
但是,当我这样做时,对超类构造函数的调用不起作用,因为它认为我的类是 Object 的子类,而不是 Level 的子类。
我知道我可以通过使用超类的参数编写重写方法然后将 Level 和 Score 转换为 MastermindLevel 和 MastermindScore 来使代码工作,但我希望了解如何/是否可以使用泛型来完成。我真的很想更彻底地了解泛型。
感谢您的帮助。
【问题讨论】:
-
你做错了。您很可能想要
<T extends Level> boolean isWin(T level)之类的东西。
标签: java generics inheritance wildcard overriding