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 Java Objects (Retired) Meet Objects Privacy and Methods

Privacy and Method...WHY?!!!!

What is the purpose of method and privacy?! Like why should I give a care?!

1 Answer

Michael Hess
Michael Hess
24,512 Points

Hi SGT Awesome,

There is a fundamental concept in object oriented programming called encapsulation.

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.

The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.

If you're interested, you may want to read over this: Encapsulation

Hope this helps! If you have any further questions I'll be happy to answer them!

Charles Franklin
Charles Franklin
17,535 Points

So Michael,

Your saying that if we were to create this program, compile it and distribute it, people could still change our code? So instead of Yoda, someone could come in and change the final program to say R2D2.

I feel like I've only got a nibble of the pie and not the whole picture..

chip