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

What is the role of a constructor?

I didn`t quite get what is the role of a constructor within a Class. Is it to define the values of the member variables?

Couldn`t I just assign values to variables directly?

1 Answer

You could individually change attributes after the creation of the object, but sometimes you want to set it only once (so it would make sense to only do so in the constructor, so you don't create a setter for that attribute).

You also could be in situations where you want to ensure objects have certain member variables have been assigned, otherwise it could break your code. It also makes your code cleaner, but not having to have extra lines to set values after object creation.