不能将A类转换为B类

时间:2012-04-15 17:56:00

标签: java oop

level的实例访问字段Minotaur的正确方法是什么? 在for (int i =0 ; i < ((Monster) this).level ; i++) Cannot cast from Player to Monster中收到错误。

package player;

import monsters.*;

public class Player extends GameCharacter {

      public void performAttackOn(GameCharacter who){

    if (who instanceof Monster ){

        for (int i =0 ; i < ((Monster) this).level ; i++) { // << 

                 }

    public static  class Minotaur extends Monster{ // << nested class which is being created and there is need to access it's level

        public Minotaur () {

              type = "Minotaur";

        }
    }

}

package monsters;

public class Monster extends GameCharacter{

    public int level = 1;
}

package monsters;

public abstract class GameCharacter{

public static  class Minotaur extends Monster{

        public Minotaur(){
            type = "Minotaur";
             hitPoints = 30;
             weapon = new Weapon.Sword();

        }
    }
}

Minotaur应扩展monsters.GameCharactermonsters.Monster并覆盖Player.playermonsters.GameCharacter继承的某些方法

4 个答案:

答案 0 :(得分:4)

GameCharacter界面定义getLevel()方法MonsterPlayer两种方法。

public interface GameCharacter
{
  public int getLevel( );
}

一旦你完成了这项工作,你就会利用polymorphism,甚至不需要施展。


另外,您是否真的要将类型为this的{​​{1}}投射到Player?或者你的意思是:

Monster

答案 1 :(得分:1)

在您定义的层次结构中,Player永远不会是Monster,因此无法进行投射。

根据上面的检查,我认为您遇到问题的行应该引用who而不是this

for(int i = 0; i < ((Monster)who).level; i++)

答案 2 :(得分:1)

这很容易。你检查who是否是Monter,但如果是,你将this投射到Moster,而this指的是你当前的女巫对象,这意味着一些玩家。替换这个

((Monster) this).level

用这个

((Monster) who).level

并且错误应该消失。

答案 3 :(得分:0)

编辑:现在我明白了,你不能在类的字段上继承。你应该有一个共同的方法

pubic int level();

GameCharacter中。然后,您可以选择将level定义为子类的两个不同字段(不推荐),或者只留下GameCharacter以获得级别字段。

此处:((Monster) this).level您要投放this个实例,PlayerMonster。这就是你得到错误的原因。

也许你的意思是:

if (who instanceof Monster ){
  for (int i =0 ; i < ((Monster) who).level ; i++) { // << 

  }
}