[英]Can a method of a subclass of an abstract super class return a super class of the super class return type?
[英]Can a subclass be referred to as the type of its super class?
我在学校玩游戏。 我的武器是物品的子类。 我有一个字段currentWeapon
在我的课称为BattleGround
。 而且,我有一种方法可以搜索和迭代“背包”中的所有项目。 我希望也将其用于武器,因为它们也是物品。
我希望的是, Weapon
类的对象也可以称为项目。 但是我只是不知道。 我需要一种新方法来遍历Weapon
吗? Weapon
和Item
都应存放在同一背包中。
如果我将currentWeapon
字段currentWeapon
为Weapon
,则无法使用该方法,也可能无法将Weapon
存储在String
和Item
的Hashmap
中。 如果将其存储为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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.