DEV Community

Discussion on: Explain Encapsulation and Polymorphism Like I'm Five

 
dance2die profile image
Sung M. Kim

Yes, and also able to find gaps in our knowledge.

My gap -> Abstraction vs Encapsulation.

Okay I am a bit confused between Encapsulation and Abstraction. I thought Abstraction was about hiding implementation and Encapsulation was about hiding data. I would appreciate it if you could explain Abstraction as well :D

And wonderfully, answered

Encapsulation is only if you want or not expose something. It could be only one thing no matters what it do. For example: you have a class to calculate a salary with two methods: GetMonthlyWage() and GetWeeklyWage(). Inside the first one you only call GetWeeklyWage() and multiply by 4. Every one could call the first method, then it's public. But you decide if you want the others could see and call GetWeeklyWage() or not. If not, you make it private. The abstraction could use encapsulation, but it is about how a method can be implemented. An abstract class is a template and each implementation of the class (concrete class) could implementate a different way to do something. No matters if it is public or private (or other access modifyer). Then, for contractor employees you could implementate the GetMonthlyWage() giving a bonus and for external workers you could implementate GetMonthlyWage() without the bonus.