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

Private vs Public

When and why should you use private/public/protected. I would like help understanding this, and why not just make everything public? Thank you for the help !

1 Answer

Restricting access with private/protected/package access modifiers is used to hide the inner workings of an object. Hiding information like this leads to cleaner and more stable interfaces (the public part). If the interface stays more-or-less constant, then the internals can change with little to no impact on dependent objects.

This also allows for finer control of the data, e.g. a setter that has checks to prevent values in a certain range from being assigned. If you had direct access to that property, you could just set it to whatever you wanted.

So you'll normally have your properties declared private or protected as they're dealing with the data structure of the object, rather than what it can do.

This ties in with encapsulation, one of the four core principles of object oriented programming.

Thanks i think I need more experience to understand the concept better, but it is definitely making more sense now.