我在学校玩游戏。我的武器是物品的子类。
我的课上有一个名为currentWeapon的字段BattleGround。而且,我有一种方法可以搜索和迭代“背包”中的所有项目。我希望也将此用于武器,因为它们也是物品。

我希望的是Weapon类的对象也可以称为项目。但是我只是不知道。我是否需要一种新方法来遍历WeaponWeaponItem都应存储在同一背包中。

如果将字段currentWeapon存储为Weapon,则无法使用该方法,并且可能无法将Weapon存储在HashmapStringItem中。如果将其存储为Item,则不能使用Weapon类的方法。谢谢。

最佳答案

如果WeaponItem的子类,则可以将Weapon存储在Item对象的集合中,而不会出现任何问题。也许您需要学习的是instanceof运算符:

List<Item> items = new ArrayList<>();

// add some items to the list

for (Item item : items) {
  if (item instanceof Weapon) {
    Weapon weapon = (Weapon) item; // cast the item to a weapon
    weapon.someWeaponMethod();
  }
}


如果使用instanceof,则可以确定Item实际上是否是Weapon

关于java - 子类可以称为其父类(super class)的类型吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15805621/

10-09 00:24