简体   繁体   中英

Passing a class instance into another class

I've looked everywhere but I can't seem to find an answer to this.

If I have one class (say, a Resource class) and another class (say a Sprite class) and each time I create a sprite, I pass in a reference to my Resource class (because it's required for some function) - am I correct in assuming, that all this does is creates a reference to this instance of said class?

So - if my Sprite constructor is this:

public Sprite(Resource res){

res.doSomething........

}

And I create 100 sprites, then this isn't going to cause problems because it's just passing in a reference or 'pointer'? (as opposed to creating a new instance each time).

Simple enough question I know, but I want to make sure I understand what's happening here and I couldn't find the answer to this anywhere.

Yes, if you create a new Sprite and pass it an existing Resource , the new Sprite will just have a reference to your original object.

So 100 Sprites would have 100 references to your 1 Resource.

是的,您每次必须创建该类的new实例来调用该特定instance. doSomething() 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