从另一个类获取子类的实例 [英] Getting an instance of a subclass from a different class

查看:176
本文介绍了从另一个类获取子类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用光滑的2D引擎和我自己的实体引擎编写游戏,以计算2D侧面滚动条的细节

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:

实体类保存实体信息.它可以具有一种能力,例如动画,声音或动作.所有功能都是名为Ability的抽象类的子类.

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.

我在Entity类中有一个方法,希望获得一个特定功能的实例,以便可以使用其方法:

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

但是,这仅返回超类Ability的特定实例.我希望从另一个包或类中获得子类的实例.

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

推荐答案

我认为您的代码已经在执行您想要的操作.如果您的ablitites集合已经保存了AnimationSoundMovement对象的实例,那么这就是您的方法将返回的内容.它只是通过Ability 引用返回它们.它不能返回超类Ability的实例,因为那是一个抽象类.您应该能够调用在Ability中声明的通用方法,并看到该方法返回的对象表现为您所请求的特定子类的实例.

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.

这篇关于从另一个类获取子类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆