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 trial

Java Java Objects (Retired) Creating the MVP Prompting for Guesses

Lucas Caldeira
Lucas Caldeira
977 Points

what does these lines do ? private Game mGame; public Prompter(Game game) { mGame = game;

public class Prompter { private Game mGame;

public Prompter(Game game) { mGame = game;}

2 Answers

Christopher Augg
Christopher Augg
21,223 Points

Hello Lucas. Let's see if we can understand these lines better.

public class Prompter { // Start class definition. Make public and name it Prompter

  /* This is a member field (variable) even though it is using an object type to reference a Game object. It is important to   
    * remember that in Java, no variable can ever hold an object. A variable can only hold a reference to an object. This means 
    * that mGame can hold the memory address of an instantiated Game object. This is different than the primitive data 
    * types like int, double, etc. Those can hold actual values (i.e  private int numCars = 3; ). 
    */
   private Game mGame;   

 /* This is the constructor for the Prompter class that is called upon instantiation of a prompter obj. Notice that it is passing a
   * reference to a Game object named game. Again, this is a reference only. Therefore, mGame gets assigned the memory 
   * address of game. This is not a good practice because it violates encapsulation. mGame was set as a private field, but since 
   * the memory address was passed by reference to the constructor, any changes to the game object outside the Prompter 
   * object will still change for mGame inside it as well because both variables are essentially referencing the same object.
   */
  public Prompter(Game game) {        
    mGame = game;
}

} // End class definition

I hope that helps

Lucas Caldeira
Lucas Caldeira
977 Points

makes sense now thank you !

Yongshuo Wang
Yongshuo Wang
5,500 Points

This is line is declare a variable with type Game, in the constructor set the value from this variable.