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

Android Build an Interactive Story App (Retired) The Model-View-Controller Pattern Adding Custom Constructors

Point of setters and constructors?


I am asking what is the point of having both setter methods and constructors that do the same thing? Are they not just taking in a parameter from an external call to the class or method, and passing in the parameter to an internal private member variable? Im not complaining or whining about the fact that there is a need to do this. I know there must be a real reason for the presence of these concepts. I just want to know the underlying logic and theory behind creating both of them at the same time.

2 Answers

Jon Kussmann
Jon Kussmann
Courses Plus Student 7,254 Points

In a constructor you can set the member variable right when you create the object with a parameter, like you said.

Where a setter can be useful is if you decide to change that value later on, or if you don't want an initial value for a member variable until some time after the object has been created.

Thanks so much!!

Henrik Hansen
Henrik Hansen
23,176 Points

The fields that is set within the constructor is a quick end easy way to set up an object with required data, to make sure everything is in there for the class to work properly, and additional constructors can be set up for several default cases.

The getters and setters are not really required, but is a good practice. If you create them in all of your classes, you wont have to go back to that class and create them when needed - you will know they are there already. They also give the benefit of being able to keep all your class member fields private.