re: Explain Encapsulation and Polymorphism Like I'm Five VIEW POST


People relate to you based on what‘s observable: how you look, and how you communicate and behave. That is publicly visible. But what you really think, and your inner workings are a secret. It‘s private.
It‘s encapsulated.

Objects in object oriented programming languages keep secrets as well. The main reason: other objects should not care about their inner workings (i.e. the implementation details), they should only care about their public behavior.

Because if these other objects only care about the public behavior (i.e. they only call the public methods), the implementation details can be changed without affecting the other objects. And that’s really good.

Let’s say I am the public sort method of a sorter object. Somebody hands me a collection of things, I sort them by age and return them. The process of determining the age is really complicated and slow, I need to call a lot of my other methods. All of these methods are private, it’s none of your business how I get things sorted.

Then one day, I discover that the creation date is printed on each of the things you pass to me. Cool! Calculating the age now involves calling fewer methods than before (and they are all private).

The other objects will only notice that I can sort now a lot faster. But as they do not depend on my inner workings, their code doesn’t have to change. They still pass in the exact same collection to be sorted, and get it back sorted.

The compiler makes sure that nobody from the outside can call my private methods.
That‘s encapsulation.

code of conduct - report abuse