Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialBrendan Passey
999 Pointsthis.game = game does it create a copy or does it make prompter refer to literally the same object created in Hangman.ja
In the prompter class, we declare an instance of game and then kind of copy the state of the instance of game created in Hangman.java when we say this.game = game. Are we simply making a carbon copy of the state of the one created in Hangman.java(the one with the answer passed in) or are we literally asking prompter to refer to the same INSTANCE of the class created in Hangman.java?
In other words if something about the instance of Game created in Hangman.java changed would the instance of Game in Prompter.java know about it without this.game = game again later in a prompter method or something?
3 Answers
Steven Parker
231,172 PointsThat's exactly right. Simple assignment of a complex object makes a reference to the same object.
If you want a copy (new instance) of an object, you can use the "Clone()" method.
Brendan Passey
999 PointsThanks for replying so quickly again Steven!
Brendan Passey
999 PointsThe pieces are falling into place Steven. Hypothetically though in that case Steven Parker would it still work if you called it something else in the prompter class? eg
private Game prompterGame;
public Prompter(Game prompterGame) { this.prompterGame = prompterGame; }
Could you just hypothetically proceed to refer to the same object with 2 different names depending on whether you are using it from?
It seems to work, is there any reason not to do this other than confusion?
Steven Parker
231,172 PointsMaking it work is certainly job 1, but it's a "best practice" to also avoid confusion!