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

FULL DISCUSSION
 

Polymorphism: You have a tool, all it does is peel fruit, no matter what kind of fruit. So when someone hands you a fruit basket, you don't sweat it, you know you can peel it all.

Contrast that with a citrus juicer, if some one hands you a basket of apples, you can't figure out how to use them with the juicer.

So polymorphism is a way to write code concerning a parent class, and any class that inherits from that parent class is valid input for that piece of code. The "standard" example is that an array of Animal objects- whether it's Dogs, Cats, Birds, whatever- can all call some Animal.speak() function. Each specific animal class implements this different and we get a variety of output.


Encapsulation: You need me to run to the grocery store for you every week. All you do is hand me your credit card, your grocery list, and your car keys and I go. Then after some time, I come back with everything you ask for. You don't know how I get there, what I do on the way, etc. You just know that when you give me the list, money, and keys, I turn it into groceries somehow.

Encapsulation is just the idea that no one outside of the programmer needs to know how parts of objects work. There is a certain part they can see and use, but that's it. So if the implementation changes because the original programmer modified something, the user of their code doesn't have their code suddenly not work.

code of conduct - report abuse