简体   繁体   中英

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.

I am using the LibGDX framework to develop a mobile game and trying to make use of its Stage and Actor classes.

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. 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. The Actor hold reference to the Stage but only the "Stage", eg the Actor class has the getter;

public Stage getStage () {
    return stage;
}

So, clearly I don't understand Java very well. 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. When this happens, does Java just ignore my extended class?

How can I call my StageExtension instance from the Actor without copying and modifying these core classes?

Hope this makes sense, thanks.

What you're seeing there is an example of Casting . What you've done is subclassed Stage with your new class StageExtension. So in your case all StageExtensions are Stages but not all Stages are StageExtensions. With that being the case Java can Cast a StageExtension to a 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. In the Actor class it will be treated as a Stage, because that's what it thinks it is to all intents and purposes. This will work because a StageExtension is a subclass of 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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