访问字段的正确方法是什么 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
的方法
最佳答案
有GameCharacter
接口(interface)定义一个getLevel()
方法 Monster
和 Player
两者都实现。
public interface GameCharacter
{
public int getLevel( );
}
完成后,您就可以利用 polymorphism甚至不需要转换。
还有,你真的是想投this
吗?这是类型 Player
, 输入 Monster
?或者你的意思是:
public void performAttackOn(GameCharacter who)
{
for (int i =0 ; i < who.getLevel( ) ; i++)
{
// do stuff...
}
}
关于java - 无法将 A 类转换为 B 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10164558/