简体   繁体   中英

How do I get an object that's declared in another object from another object declared in the parent object

public class MainThread extends Thread implements Runnable{

    GameScreen g;
    ObjectManager om;

    public MainThread(){

    }

}

So What I want to do is inside the GameScreen object in MainThread, I want to get the ObjectManager object from inside the gamescreen. So the way I'm looking at this situation is that there must be a keyword that is used to refer to the object the object is inside, and then refer to the object inside the parent.

public class GameScreen{
    public GameScreen(){
        // ObjectManager test = this.*parent object*.om;
    }
}

Since you didn't include your full code things are a bit unclear.

If GameScreen is declared elsewhere (eg, in another file), then it can technically be placed anywhere - an instance of GameScreen doesn't have to be within a MainThread so it has no access to ObjectManager instance. You will have to define a constructor to GameScreen that takes an ObjectManager instance, and then in the constructor of MainThread initialize g with your om.

If you only want to use GameScreen within MainThread (not necessarily the best design) you can make it in a non-static inner class. If you defined the entire GameScreen class inside MainThread, then every GameScreen instance will have a (hidden) reference to the containing MainThread and thus to the om instance.

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