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 Harnessing the Power of Objects Filling the Dispenser

Sarmishta Chaitanya
Sarmishta Chaitanya
2,204 Points

Need clarification - Encapsulation and Abstraction

There's always a confusion in my mind between encapsulation and abstraction. Both seem very similar to me. Can someone please clearly explain the difference between these two concepts with few examples?

2 Answers

Yanuar Prakoso
Yanuar Prakoso
15,196 Points

Hi there..

Allow me to explain it in my way. In my opinion abstraction and encapsulation are related but often distinctive in terms of point of view. Abstraction is more of customers or in this case users point of view and encapsulation is how to make such abstraction. Okay before it gets confusing let us just review the Pez Dispenser in the video.

For the users when they order PEZ they expect to have PEZ with head, which has character head chosen by them, and dispenser filled full by candies. They do not want to know how but they know that they will get exactly those specification. This is abstraction.

The other party involved here is the developers. The developers knows that the users expect to have PEZ with character head of their choice and dispenser full of candies. The users do not need to know how the developers made it. Therefore to achieve this kind of abstraction the developers use technique called encapsulation which provide a mechanism to restrict access to method therefore hiding the means of how it is done to the users. Once the code compiled the users will not have access to see the source code on how the method is done.

Thus when the developers encapsulate the part how they fill the dispenser with candies to its' maximum capacity the users will not get to see how it is done. The developers only ensure the users that they will get the job done. Therefore the users will get their PEZ with character head of their choice and dispenser filled with candies to the maximum capacity.

I hope this will help. Any other inputs are welcomed.

Yanuar Prakoso deserves a :clap::clap::clap:

Thank you for such a great explanation.