The 4 pilars of OOP

If you want to be a good developer you must understand and use the four pillars of OOP. In this post we will talk about them and see some examples on their use.

Abstraction

Abstraction

Using an analogy with a car. You buy a car and just need to know how to make your car go forward or backward, at maximum if you have a manual car, how to shift gears. You don't need to know how a "Otto engine" works, what means admission, compression, combustion and exhaust, how the transmission gears work, how it's power is transmitted to the wheels, etc. You simply ABSTRACT it.

This is abstraction, the outside classes doesn't need to know how the class works internally, just what it does.

Encapsulation

Capsules

I heard this explanation a long time ago and never forgot it. Maybe, my cousin building encapsulation tools and selling it to pharmacies, helped me to keep this memory. Well anyway...

When you buy a medice capsule you don't need to know exactly what goes inside. Maybe there is iron, vitamin c and phosphorus. Or maybe there is Acetoxybenzoic acid. All this componets are relevant only for the maker of the capsule, you just need to feel better.

Encapsulation is the habillity to hide internal properties or methods using access modifiers, like public, private or protected.

Inheritance

Inheritance

Of all the 4 pillars inheritance is the easiest one. Inheritance is almost like genetics, quoting Harry Potter: "Harry, you look like exactly your father except for your eyes. You have your mother's eyes".

Inheritance is the ability to have the same methods and properties than the parent class. A class can only extends (inherit) from one class, but we can implement multiple inheritance using interfaces.

Polymorphism

Once Bruce Lee said: "You must be shapeless, formless, like water. When you pour water in a cup, it becomes the cup. When you pour water in a bottle, it becomes the bottle. When you pour water in a teapot, it becomes the teapot. Water can drip and it can crash. Become like water my friend.". He meant by this that we should adapt ourselves to any situation.

Polymorphism

Polymorphism is the ability to have multiple behaviors, overriding the parent's methods to better adapt the class context.

I hope I've helped you to better understant the Four Pillars of OOP, and that you can write better codes with this knowledge.

Rogério Eduardo Pereira
06/02/2020