在不知道子类的情况下返回getter方法中的子类

时间:2017-08-02 16:53:34

标签: java

我有一个抽象类Item类,其子类为Weapon ShieldPotion

abstract public class Character {

    private Item item;

    public Character(Item item) {
        this.item = item;
    }

    public Item getItem() {
        return this.item;
    }
}

public class Hero extends Character{

    public Hero(Item item) {
        super(item);
    }
    public static void main(String[] args) {
        Hero h = new Hero(new Weapon("sword"));
        System.out.println(h.getItem().getDamage());
        /* getDamage is not known because it is not a method of the Item
           class, it is a method of the Weapon class */

        Hero h1 = new Hero(new Potion("syrup"));
        System.out.println(h1.getItem().getPower());
        /* again getPower() is not known */
    }
}

我该怎么办才能将this.item作为Weapon/Potion...而不是Item返回。我已经完成了研究,并且我需要将方法public Item getItem()更改为方法public <T extends Item> getItem()或将this.item转换为Weapon/Potion/Shield,但我无法弄清楚如何这样做。

2 个答案:

答案 0 :(得分:1)

abstract class Character
{
    private Item item;

    public Character (Item item)
    {
        this.item = item;
    }

    public <T extends Item> T getItem (Class <? extends T> targetType)
    {
        return targetType.cast(this.item);
    }

    public void setItem (Item item)
    {
        this.item = item;
    }
}

class Hero extends Character
{
    public Hero (Item item)
    {
        super (item);
    }

    public static void main(String[] args) {

        Hero hero1 = new Hero(new Weapon("sword"));
        Weapon weapon = hero1.getItem(Weapon.class);
        hero1.setItem(new Potion("syrup"));
        Potion potion = hero1.getItem(Potion.class);
    }
}

答案 1 :(得分:0)

我应该像这样使用“cast”:

if (this.item instanceof Weapon)
{
   ((Weapon) this.item).fire() ;
}
else if (this.item instanceof Potion)
{
   ((Potion) this.item).drink() ;
}
else // Shield
{
   ((Shield) this.item).defend() ;
}