我在学校玩游戏。我的武器是物品的子类。
我的课上有一个名为currentWeapon
的字段BattleGround
。而且,我有一种方法可以搜索和迭代“背包”中的所有项目。我希望也将此用于武器,因为它们也是物品。
我希望的是Weapon
类的对象也可以称为项目。但是我只是不知道。我是否需要一种新方法来遍历Weapon
? Weapon
和Item
都应存储在同一背包中。
如果将字段currentWeapon
存储为Weapon
,则无法使用该方法,并且可能无法将Weapon
存储在Hashmap
和String
的Item
中。如果将其存储为Item
,则不能使用Weapon
类的方法。谢谢。
最佳答案
如果Weapon
是Item
的子类,则可以将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/