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 Android Lists and Adapters (2015) Using Parcelable Data Using a Creator and Reading a Parcel

Ashwin Kumar Kurella
Ashwin Kumar Kurella
9,984 Points

Why should we use a private constructor?

Can't we use some other method which takes a Parcel object as a parameter, to read the contents of a parcel, instead of the private constructor?

2 Answers

Assuming you mean an instance method inside the Day class, it could certainly take a Parcel as a parameter like you said. But where would the Parcel data be assigned? And how would that method even be invoked in the first place? To invoke it we'd have to already have an instance of Day, and that means we'd probably have already set all of its fields!

We want to make a new instance of Day using data from the Parcel object, so that's why it's in a constructor, not an instance method. Why private? Because generally you want to strive to give the least amount of access necessary to any data within the code you write. In the Day class, it looks like Ben only intended the static Creator<Day> object instance to use that constructor, so he limited the constructor's access to private. He could've made it public, but that would raise the questions: where outside the Day class is it being used, and why does it need to be used there? At this point in the project it didn't need to be used anywhere else, so it wasn't enabled to be used elsewhere.

J.D. Sandifer
J.D. Sandifer
18,813 Points

In the video, Ben explained that "This is all a pattern that the Android system understands and expects to be in place. It may seem like a lot of work, but it makes our data available to use wherever Android uses parcelable data."

Sometimes the quick explanations like that can get lost among the sea of information contained in the videos - it's definitely happened to me a few times.

Hopefully that helps!