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

Understanding Java getCharacterName

Hey guys,

I'm trying to make sure I understand why I am doing everything in the videos rather than just copying Craig, so I'm writing notes along side each code block. In the code below we have;

public PezDispenser (String characterName) {
  mCharacterName = characterName;
 mPezCount = 0;
}

which I think means we have created a variable so we can add the name of the character without exposing the member variable.

But then further down the code we have

public String getCharacterName() {
return mCharacterName;
}

And I'm not really sure why we have added this, it feels like we are repeating ourselves? Why can't we call characterName instead of getCharacterName?

I think I've confused myself a bit and got in a tangle!

2 Answers

Hi, Stephanie: mCharacterName is a private variable in the PezDispenser class; it cannot be accessed outside the class. In order to make its value visible to users of PezDispenser, you have created a getter -- getCharacterName -- which does nothing but return the value of mCharacterName.

If you want users of PezDispenser to be able to change the value of mCharacterName, you could add a setter -- setCharacterName -- to which a user would pass a new value; inside the setter, you could perform any appropriate validation, then set mCharacterName to the new value.

Hope that helps!

Hi Phil, thats brill thanks for the reply. It all makes sense now! I just confused myself big time haha