我有一个抽象类Item
类,其子类为Weapon
Shield
和Potion
。
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
,但我无法弄清楚如何这样做。
答案 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() ;
}