gpt4 book ai didi

java - 无法将 A 类转换为 B 类

转载 作者:行者123 更新时间:2023-11-30 05:53:49 25 4
gpt4 key购买 nike

访问字段的正确方法是什么 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()方法 MonsterPlayer两者都实现。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com