gpt4 book ai didi

java - 在 getter 方法中返回子类而不知道子类

转载 作者:行者123 更新时间:2023-12-02 12:26:21 26 4
gpt4 key购买 nike

我有一个抽象类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但我不知道该怎么做。

最佳答案

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

关于java - 在 getter 方法中返回子类而不知道子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45466740/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com