从不同的类获取子类的实例
我正在使用光滑的 2D 引擎和我自己的实体引擎编写一个游戏,以计算出 2D 侧向滚动条的细节。
我的代码当前的工作方式是这样的:
实体类保存实体信息。它可以有一种能力,比如动画、声音或运动。所有能力都是称为能力的抽象类的子类。
我在实体类中有一个方法,我希望获取特定能力的实例,以便我可以使用它的方法:
public Ability getAbility(String id) {
for(Ability abil : ablitites) {
if(abil.getId().equalsIgnoreCase(id)) {
return abil;
}
}
return null;
}
但是,这仅返回超类能力的特定实例。我希望从不同的包或类中获取子类的实例。
执行此操作的代码示例将不胜感激。谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不完全理解你的问题,但我认为你应该看看 Casting< /a>.
我认为你应该像这样使用你的代码:
(当然,我不知道你的设计,所以我猜测一下)
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)
我认为你的代码已经在做你想做的事情了。如果您的
ablitites
集合已包含Animation
、Sound
和Movement
对象的实例,那么这就是您的方法所要做的返回。它只是通过Ability
引用返回它们。它无法返回超类Ability
的实例,因为它是一个抽象类。您应该能够调用Ability
中声明的常用方法,并看到您的方法返回的对象充当您请求的特定子类的实例。I think your code is already doing what you want. If your
ablitites
collection already holds instances ofAnimation
,Sound
, andMovement
objects, then that's what your method will return. It just returns them through anAbility
reference. It can't return an instance of the superclassAbility
since that's an abstract class. You should be able to call the common methods declared inAbility
and see that the objects returned by your method behave as instances of the specific subclasses that you request.