Getting an instance of a subclass from a different

2019-08-29 09:44发布

问题:

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.