繁体   English   中英

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

[英]Can a subclass be referred to as the type of its super class?

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

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

如果我将currentWeapon字段currentWeaponWeapon ,则无法使用该方法,也可能无法将Weapon存储在StringItemHashmap中。 如果将其存储为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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM