简体   繁体   中英

Accessing subclass methods by referencing superclass

I have a superclass called "Items" and a sub class called "PickUpHealth1". I create an array of Items similar to this code:

ArrayList<Items> itemsArray = new ArrayList<Items>();
Items h1 = new PickUpHealth1(x,y);
itemsArray.add(h1);

The subclass has it's own methods. I go through the array itemsArray and when a certain event occurs I want to initiate methods in the subclass PickUpHealth1. I know that the superclass doesn't know about the methods in the subclass but I don't want to create a separate array for each subclass if possible. Is there anyway I can reference the methods in the subclass through itemsArray? Since h1 is initialized as an object of PickUpHealth1 I would think there should be a way to do this, but I can't figure it out. Is there a way? Or am I going about it all wrong? Thanks.

So PickUpHealth1 extends Item and you have a List<Item> items

As you've noted Item s can only do Item things, so you can't go trying to use PickUpHealth1 methods when you are accessing it as an Item through the items list.

If Item s don't have anything in common then don't extend from it.

If they are all "useable" then give them a common method.

For example:

abstract class Item {
    public abstract void useItem();
}

class PickUpHealth extends Item  {
    private int healAmount;
    public PickUpHealth(int healAmount) {
        this.healAmount = healAmount;
    }

    @Override
    public void useItem() {
        player.addHealth(healAmount);
    }
}

public static void main(String[] args) {
    List<Item> items = Arrays.asList(new PickUpHealth(10));
    Item item = items.get(0);
    item.useItem();
}

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