我正在学校制作游戏。我有武器,它是元素的子类。
我的类中有一个名为 BattleGround
的字段 currentWeapon
。我有一种方法来搜索和迭代我的“背包”中的所有项目。我希望也将其用于武器,因为它们也是元素。
我希望的是 Weapon
类的对象也可以称为项目。但我就是不知道。我是否需要一种新方法来迭代Weapon
? 武器
和元素
都应存放在同一个背包中。
如果我将字段currentWeapon
存储为Weapon
,我将无法使用该方法,并且可能不会将Weapon
存储在中
。如果我将其存储为 String
和 Item
的 >HashmapItem
,我将无法使用 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/