Welcome to the Treehouse Community
Looking to learn something new?
Anas Rida8,183 Points
return characterName directly
why can't we return the characterName directly from the constructor?? without having to define a private string variable mCharacterName. Many thanks
I'm afraid that this would be really bad practice. Java was built to have multiple objects of a single type. And I believe what you're asking would be to define mCharacter Name in our code. That means that every object of this type (in this case pez dispenser) would all have the same name. We have constructors so that we can have multiple objects of different types of names.
Let's say for instance we have a person object, we want to set our constructor up to be a blank slate until we assign that person a name. If we just hard-coded bob, then we'd all be named bob, as we'd have no way to set a value in our constructor.
Thanks, hope this helps.
Anas, I also believe this goes hand in hand with encapsulation. Which is a pretty necessary step in safe coding. This practice allows you to make the code less malleable and limit the options that the users will have when interacting with your finished product, allowing them to only change and manipulate the date the way you intended.
Use of the constructor along with the get and set properties makes it so there is a way for users to choose from preselected options (like car colors) or pass in values (names, dates, etc) while only effecting that instance of the class. The setter will then apply that change in value to the instance and the getter will call on that data when necessary throughout the life of the program or the object.