Jon
Jon

Reputation: 2410

Confusion with Java generics and subclassing

I have the following:

I then have:

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

Answers (1)

Andrew Mao
Andrew Mao

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

Related Questions