子类可以称为其超类的类型吗?

时间:2013-04-04 08:01:15

标签: java subclass superclass

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

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

如果我将字段currentWeapon存储为Weapon,我无法使用该方法,也可能无法将Weapon存储在Hashmap String中s和Item s。如果我将其存储为Item,则无法使用Weapon类的方法。谢谢。

1 个答案:

答案 0 :(得分:2)

如果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

相关问题