Object-Oriented Programming ( OOP ) is a computer programming model that organizes software design around data, or objects, rather than functions and logic. There are 4 pillars of OOP :
- Abstraction
- Polymorphism
- Inheritance
- Encapsulation
In OOP everything is an object and it focuses on creation of these objects. I’ll explain every principle and give examples using Ruby - an Objected Oriented Programming language
Encapsulation
I’ll start with Encapsulation which means wrapping up data in a single unit. Binding all the code and data into a class. Basically, the variables and data of a class are hidden from everything else and only can be accessed through any member function of their own class which they are declared
Example :
In the example, I can easily change the name of the dog from Sasha to Shiba without knowing how the Dog class is implemented or how the class is storing values in the variables. Helping to improve the security and easier to test the code
Inheritance
Inheritance allows an object to take properties and methods of another object. So simple isn’t it. Here is the example :
I created 2 class, Animal and Dog. I made the Dog to inherit the “eat” method from Animal class using the “ < “ keyword so the dog could eat like an animal. In this case, the Dog class is called “child class” or “subclass” and the Animal is called “parent class” or “superclass”. A child class can reuse any data or code from its parent class.
Polymorphism
Polymorphism can be understood as “many forms” or “many shapes”. We can understand it means a child class can have all of the functions and data from its parent class but it can obtain different results using the same function by changing the return value
Example :
In this case, the Dog class and Cat class are both inherited the Animal class, they share the same “speak” method. But you can override it so a dog and a cat can speak differently.
Abstraction
Data abstraction is a technique when you only focus on important details. Abstraction is trying to minimize information so that the developer can concentrate on a few ideas at a time. In ruby, we have access specifiers ( public, private, protected ) that will determine which information should be visible and which is not.
In this example, the “taking_shower” method is private and cannot be accessed directly, we can call “go_home” method in order to access it. This technique helps increase the security of a system because only crucial details are made available to the user and prevents redundancy of code
Thanks for reading !
Last Words
Although my content is free for everyone, but if you find this article helpful, you can buy me a coffee here