mRambech mRambech - 1 month ago 9
Java Question

How do i get this search method to work for sub-classes as well as the the super-class?

This is a piece of a class thats called Player. findItem() is the method that's used to return an Item from the HashMap "items".

public class Player extends Character {
private String type;
private int carryWeight;
private HashMap<String, Item> items;


public Item findItem(String search) {
return this.items.get(search);
}


This method has been working fine until now.
Now, i have a subclass for Item, called Weapon.

public class Weapon extends Item{
private int damage;

public Weapon(String name, String description, String action, int value, int weight, int damage){
super(name, description, action, value, weight);
this.damage = damage;
}

public int getDamage(){
return damage;
}


}

I can add a Weapon to the items HashMap in Player because Weapon is just an extension of Item. I can also use findItem() to find the weapon in the HashMap, but it returns it as an Item and not a Weapon. This makes it so that i cannot use the getDamage() method from the weapon subclass. Does anyone see a quick solution to my problem? Im pretty sure its something im missing about inheritance.

I tried writing this method, but it says it cannot convert Item to Weapon:

public Weapon findWeapon(String search){
for (Weapon weapon : items.values()){
something somthing
}
}

Answer

You could use instanceof to sort out Weapon instances. For example:

public Weapon findWeapon(String search){
  for (Item item : items.values()) {
    if(weapon instanceof Weapon) {
      Weapon weapon = (Weapon)item;
      <something somthing>
    }
  }
}