有以下接口类:
public interface IGameObject {
String gameObjectID();
String gameObjectName();
void isActionValid(String action);
void viewActions();
}
我有一个抽象类,实现了上述接口。
package gameprobjectpackage;
public abstract class Weapon implements IGameObject {
//Left out getters/setters to keep it simple
private String gameOjectID;
private String gameObjectName;
private int damage;
public Weapon(String gameOjectID, String gameObjectName,int damage) {
super();
this.gameOjectID = gameOjectID;
this.gameObjectName = gameObjectName;
this.damage = damage;
}
我看到一些帖子建议避免向下转型。我理解其中的原因,但是我的问题是如果我需要访问一个特定于子类的方法怎么办。例如:
public class ChargeGun extends Weapon {
private String [] chargeGunActions;
public ChargeGun(String gameOjectID, String gameObjectName, int damage) {
super(gameOjectID, gameObjectName, damage);
chargeGunActions = new String [3];
chargeGunActions[0] = "Charge and Fire";
chargeGunActions[1] = "Release";
chargeGunActions[2] = "Drop Gun";
}
//This method is only meant for gun, and this type of gun is the only one in my game.
//This method, I don't belive should be in the abstract method weapon, because NOT every weapon is a gun.
public void reloadGun()
{
}
我将其存储在一个库存哈希表中,如下所示:
Map<String,IGameObject> inventory = new HashMap<String,IGameObject>();
当我检索它时,我会得到一个 IGameObject
,如何正确地转换它,以便我可以访问ChargeGun
中的方法?
InventoryMap
类,并添加一个#getItems(Class<?> clazz)
方法,这样你就可以通过调用inventory.getItems(ChargeGun.class)
来检索一个Map<ChargeGun>
。有了新创建的枪支映射表,你可以随心所欲地进行操作。向下转型将在getItems()
方法内部发生。只有当你计划一次性处理同一类对象时,才有意义。否则,请实现特定的获取器,例如#getGun(String key)
。但是请注意,如果键匹配的对象不是枪支,则要小心所需的行为。 - Paulo Avelar