1

我有以下内容:

  • 一个抽象类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 错误的情况下运行。任何指针将不胜感激。也许我把事情弄得太复杂了?

4

1 回答 1

1

您应该声明它MyScoreRecord实际上是 的子类BaseScoreRecord,并正确参数化它:

public class MyScoreRecord extends BaseScoreRecord<LevelScore>

例如,如果您使用 Eclipse,您将收到警告,因为@Override注释实际上并未覆盖任何内容。以上也将使编译器强制执行LevelScoreextends BaseScore

于 2013-03-22T04:56:38.597 回答