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 trialMike B
10,424 PointsHow are private variables changed without using the getVariable() methods?
In the pez dispenser example, we have set both the mCharacterName and mPezCount to private, but then we are able to set the value in the constructor class. I thought the purpose of setting a variable to private was so we can't directly access/change the value
2 Answers
David Lacedonia
13,627 PointsThe 'private' key protects the variable from the outside (of the object). You can open gates to that variable, with public methods (get/set).
In this case, the variable can be settled in the initialization because you want to set the variable when is created.
The purpose is that you can't access/change the variables with the dot notation: object.variable. Example: kart.color = "red"; So you create your set/get methods (if you want) to manipulate the variable, from the outside.
For example, your set method set the variable, just if the parameter length is bigger than 10. So you protect the variable from being setted with a short string.
(sorry for bad english)
Kelly Hughes
2,444 PointsHi Mike,
I'm still working on grasping the use of the private access level modifier, but I believe that it is done to reduce the probability of error within the main code. This is due to the fact that private variables can only be accessed within their class. In contrast, a public variable can be used throughout the code, and this may increase the chance of syntax error.
The get() and set() methods are still within the code of Class, so they can access the private variables. As David said previously, you can consider them as a gateway to use the variable within the main code. You give the state of the object when creating it (Object objectReference = new Object(info);, the get() method can retrieve that info due to the intialization code within the Class constructor, and then it can return that info.
So, if you want to print something out to the screen: System.out.printf("Here's some stuff about %s\n", objectReference.getMethod()); will be allow the user to see it.
Also, a tip that I just found from the Oracle Java Tutorial:
We already learned that %s is for string, however - %d is for integer %f is for float and double
I hope that this helps!
Mike B
10,424 PointsMike B
10,424 PointsI think I understand...thanks for the help.