从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.GameCharacter
,monsters.Monster
并覆盖Player.player
从monsters.GameCharacter
继承的某些方法
答案 0 :(得分:4)
让GameCharacter
界面定义getLevel()
方法Monster
和Player
两种方法。
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
个实例,Player
到Monster
。这就是你得到错误的原因。
也许你的意思是:
if (who instanceof Monster ){
for (int i =0 ; i < ((Monster) who).level ; i++) { // <<
}
}