Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Objects (Retired) Creating the MVP Storing Guesses

When do we use member variable and when non-member to call a method?

In the video Craig created a boolean method to apply a guess and then to check for a hit he used this line: boolean isHit = mAnswer.indexOf(letter) >=0;

Why can't we similarly use answer.indexOf(letter) >= 0; ?

In the constructor we set mAnswer = answer, so shouldn't it allow for answer.indexOf(letter) >=0; ?

Here is the whole code:

public class Game { private String mAnswer; private String mHits; private String mMisses;

public Game (String answer) { mAnswer = answer; mHits = ""; mMisses = "";

public boolean applyGuess(char letter) { boolean isHit = mAnswer.indexOf(letter) >=0; if (isHit) { mHits += letter; } else { mMisses += letter; } return isHit; } }

1 Answer

Corey Johnson
Corey Johnson
Courses Plus Student 10,192 Points

Hello Arthur,

That would not work due to the scope of variables. The answer String variable that is passed to the constructor is only accessible within the constructor method itself. The private class member variables (mAnswer, mHits, and mMisses) are declared at a class level, so they are accessible anywhere in the class itself.

So the value of mAnswer is set to the value of answer when a new Game object is instantiated, via the constructor method. Then any member methods within the class can now access that value (via mAnswer).

I hope this helps. Keep programming!

Yeah, I figured it out when going over the code more thoroughly, but thank you anyway!