Reputation: 2410
I have the following:
BaseScore
LevelScore
which is a subclass of BaseScore
I then have:
An abstract class 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++;
}
}
...and MyScoreRecord
which is a subclass of 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();
}
};
}
So, then I have BaseGame
which has the following line:
protected BaseScoreRecord<? extends BaseScore> endGameRecord;
...and MyGame
which is a subclass of BaseGame
. MyGame
includes the following methods:
@Override
protected void gameInit(){
endGameRecord = new MyScoreRecord(); //endGameRecord initialised
}
protected void addLevelScore(LevelScore ls){
mEndGameRecord.addScoreRecord(ls);
}
I get a compiler error on this last method:
The method addScoreRecord(capture#3-of ? extends BaseScore)
in the type BaseScoreRecord <capture#3-of ? extends BaseScore>
is not applicable for the arguments (LevelScore)
...so I am evidentially doing something wrong regarding the generics, wildcards and the subclassing. If I lose the generics in BaseGame
and MyGame
it all seems to run without any nasty ClassCastException errors. Any pointers would be much appreciated. Maybe I have made things too complicated for myself?
Upvotes: 1
Views: 329
Reputation: 36900
You should declare that MyScoreRecord
is actually a subclass of BaseScoreRecord
, and parameterize it properly:
public class MyScoreRecord extends BaseScoreRecord<LevelScore>
If you are using Eclipse, for example, you will get warnings because the @Override
annotations are not actually overriding anything. The above will also make the compiler enforce that LevelScore
extends BaseScore
.
Upvotes: 1