简体   繁体   English

Java-从包含父类的对象获取扩展类

[英]Java - get extended class from object containing parent class

I may have got the terminology wrong so I apologise, I am quite the Java rookie. 我可能用错了术语,所以我很抱歉,我是Java新手。

I am using the LibGDX framework to develop a mobile game and trying to make use of its Stage and Actor classes. 我正在使用LibGDX框架来开发手机游戏,并试图利用其Stage和Actor类。

I have created my own class, StageExtension, which is an extension of the Stage class as I have added some of my own methods to it. 我创建了自己的类StageExtension,它是Stage类的扩展,因为我向其中添加了一些自己的方法。 So lets say I have; 所以说我有;

StageExtension stageExt = new StageExtension():
Actor actor = new Actor();
stageExt.addActor(actor);

This works perfectly fine. 这工作得很好。 The problem is when I want to get the Stage from the Actor to call one of my own StageExtension methods. 问题是当我想从Actor获得Stage来调用我自己的StageExtension方法之一时。 The Actor hold reference to the Stage but only the "Stage", eg the Actor class has the getter; Actor保留对舞台的引用,但仅引用“舞台”,例如Actor类具有吸气剂;

public Stage getStage () {
    return stage;
}

So, clearly I don't understand Java very well. 因此,显然我不太了解Java。 When I add the Actor to the Stage, it calls setStage() in the Actor, so the StageExtension is successfully being set as just a Stage in the Actor. 当我将Actor添加到舞台上时,它将在Actor中调用setStage(),因此StageExtension已成功设置为Actor中的一个舞台。 When this happens, does Java just ignore my extended class? 发生这种情况时,Java是否会忽略我的扩展类?

How can I call my StageExtension instance from the Actor without copying and modifying these core classes? 如何在不复制和修改这些核心类的情况下从Actor调用我的StageExtension实例?

Hope this makes sense, thanks. 希望这是有道理的,谢谢。

What you're seeing there is an example of Casting . 您所看到的是Casting的示例。 What you've done is subclassed Stage with your new class StageExtension. 您所做的是使用新的StageExtension类将Stage子类化。 So in your case all StageExtensions are Stages but not all Stages are StageExtensions. 因此,在您的情况下,所有StageExtensions都是阶段,但并非所有Stage都是StageExtensions。 With that being the case Java can Cast a StageExtension to a Stage. 在这种情况下,Java可以将StageExtension转换为Stage。 So in your case if you do 所以如果你这样做

StageExtension somesStage = new StageExtension ();
...
actor.setStage(somesStage)

Then java will try to Cast the StageExtension someStage to a Stage for you. 然后,java将尝试为您将StageExtension someStage强制转换为Stage。 In the Actor class it will be treated as a Stage, because that's what it thinks it is to all intents and purposes. 在Actor类中,它将被视为一个舞台,因为这就是所有意图和目的的意义。 This will work because a StageExtension is a subclass of Stage. 这将起作用,因为StageExtension是Stage的子类。 To go the other way you should explicitly Cast the object 换种方式,您应该显式转换对象

if(actor.getStage() instanceof StageExtension){
    StageExtension myStage = (StageExtension) actor.getStage()
}

Now Java will do it's best to cast this object to the subclass 现在,Java会做到最好将此对象转换为子类

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

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