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) 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,459 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.