我有以下内容:
- 一个抽象类
BaseScore
LevelScore
这是一个子类BaseScore
然后我有:
一个抽象类
BaseScoreRecord
public abstract class BaseScoreRecord<T extends BaseScore> { public BaseScoreRecord(){ init(); } protected T[] mScoreHistory; protected int count=0; protected float finalScore; protected abstract void calcFinalScore(); protected abstract void init(); public float getFinalScore() { return mFinalScore; } public void addScoreRecord(T score){ mScoreHistory[count] = score; count++; } }
...
MyScoreRecord
这是一个子类BaseScoreRecord
public class MyScoreRecord extends BaseScoreRecord<LevelScore> { public MyScoreRecord(){ init(); } @Override protected void calcFinalScore(){ //Does some stuff to calc final score from mScoreHistory } @Override protected void init(){ mScoreHistory = new LevelScore[10]; for (int i=0;i<mScoreHistory.length;i++){ mScoreHistory[i] = new LevelScore(); } }; }
所以,然后我有BaseGame
以下行:
protected BaseScoreRecord<? extends BaseScore> endGameRecord;
...并且MyGame
它是BaseGame
. MyGame
包括以下方法:
@Override
protected void gameInit(){
endGameRecord = new MyScoreRecord(); //endGameRecord initialised
}
protected void addLevelScore(LevelScore ls){
mEndGameRecord.addScoreRecord(ls);
}
最后一种方法出现编译器错误:
The method addScoreRecord(capture#3-of ? extends BaseScore)
in the type BaseScoreRecord <capture#3-of ? extends BaseScore>
is not applicable for the arguments (LevelScore)
...所以我显然在泛型、通配符和子类方面做错了。如果我丢失了泛型,BaseGame
并且MyGame
它似乎在没有任何讨厌的 ClassCastException 错误的情况下运行。任何指针将不胜感激。也许我把事情弄得太复杂了?