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) Meet Objects Constructors

Anas Rida
Anas Rida
8,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

2 Answers

Rob Bridges
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Rob Bridges
Full Stack JavaScript Techdegree Graduate 35,467 Points

Hey Anas,

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.