Getting an instance of a subclass from a different class

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 14:14:33

问题


I am writing a game using the slick 2D engine and my own entity engine to work out the details of a 2D side scroller

The way my code currently works is like this:

Entity class holds entity information. It can have an Ability, something like Animation or sound or movement. All abilities are subclasses of an abstract class called Ability.

I have a method in the Entity class where I wish to get an instance of a specific ability, so that I can use its methods:

 public Ability getAbility(String id) {
    for(Ability abil : ablitites) {
        if(abil.getId().equalsIgnoreCase(id)) {
            return abil;
        }
    }
    return null;
}

However, this only returns a specific instance of the superclass, Ability. I wish to get an instance of the subclass from a different package or class.

A sample of code that does this would be appreciated. Thanks


回答1:


I don't completely understand your question but I think you should take a look to Casting.

I think you should use your code like this:
(Of course, I have no clue of your design, so I'm guessing a bit)

Ability ability = getAbility("moveLeft");
if (ability instanceof MoveAbility)
{
    // Right here, we know it IS a MoveAbility because we checked it with
    // instanceof

    // So, we can cast it to a MoveAbility.
    MoveAbility moveAbility = (MoveAbility) ability;
    moveAbility.execute();
}



回答2:


I think your code is already doing what you want. If your ablitites collection already holds instances of Animation, Sound, and Movement objects, then that's what your method will return. It just returns them through an Ability reference. It can't return an instance of the superclass Ability since that's an abstract class. You should be able to call the common methods declared in Ability and see that the objects returned by your method behave as instances of the specific subclasses that you request.



来源:https://stackoverflow.com/questions/8640171/getting-an-instance-of-a-subclass-from-a-different-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!