简体   繁体   English

通过引用超类访问子类方法

[英]Accessing subclass methods by referencing superclass

I have a superclass called "Items" and a sub class called "PickUpHealth1".我有一个名为“Items”的超类和一个名为“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.我遍历数组 itemsArray,当某个事件发生时,我想启动子类 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?无论如何我可以通过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.由于 h1 被初始化为 PickUpHealth1 的对象,我认为应该有办法做到这一点,但我无法弄清楚。 Is there a way?有办法吗? Or am I going about it all wrong?还是我做的一切都错了? Thanks.谢谢。

So PickUpHealth1 extends Item and you have a List<Item> items所以PickUpHealth1 extends Item并且你有一个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.正如您所指出的, Item只能做Item事情,所以当您通过项目列表将其作为Item访问时,您不能尝试使用PickUpHealth1方法。

If Item s don't have anything in common then don't extend from it.如果Item没有任何共同点,则不要从中扩展。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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