If you need to avoid downcasting, what should I do?

have the following interface class:

public interface IGameObject {

    String gameObjectID();
    String gameObjectName();
    void isActionValid(String action);
    void viewActions();
}

I have the following abstract class that implements the above interface.

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;
}

I came across several posts that suggest that the decline should be prevented. I understand why, BUT, my question is what should I do if I need to access a method that belongs to a subclass. For instance:

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()
{

}

I store in the interventory hashmap as follows:

Map<String,IGameObject> inventory = new HashMap<String,IGameObject>();

When I remove it, I get IGameObjecthow to place it correctly in order to access the method in ChargeGun?

+4
source share
1 answer

, . : IGameObject, (GameObjectVisitor v), v.visit(). GameObjectVisitor : , (Chargegun g), (Sword s) ..

-, : GameObjectVisitor item.accept(this), accept (GameObjectVisitor g) g.visit(this).

, / instanceof.

+5

All Articles