简体   繁体   中英

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

I am making a game at school. I have weapons which is a subclass of items. And I have a field currentWeapon in my class called BattleGround . And I have a method to search and iterate through all items in my "backpack". I was hoping to also use this for weapons, since they are also items.

What I was hoping was that an object of the Weapon class can be called an item as well. But I just simply do not know. Do I need a new method to iterate through the Weapon s? Both Weapon s and Item s are to be stored in the same backpack.

If I store the field currentWeapon as a Weapon , I can not use the method and maybe not store Weapon s in the Hashmap of String s and Item s. If I store it as an Item I can not use the methods of the Weapon class. Thank you.

If Weapon is a subclass of Item , then you can store a Weapon in a collection of Item objects without any problems. Perhaps what you need to learn is the instanceof operator:

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();
  }
}

If you use instanceof , you can determine whether your Item is in fact a Weapon .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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