Object-Oriented Programming (OOP) is a popular programming paradigm based on the concept of “objects.” It makes code reusable, modular, and easier to maintain. In this blog, we’ll dive into the 4 main pillars of OOP:
🔹 Encapsulation
🔹 Abstraction
🔹 Inheritance
🔹 Polymorphism
We’ll explore each with simple JavaScript examples to make them easier to understand.
1️⃣ Encapsulation — Hiding the Complexity
Definition: Encapsulation is the process of wrapping data (variables) and methods (functions) into a single unit (class). It restricts direct access to some of the object’s components.
Example:
class Person {
constructor(name, age) {
this._name = name;
this._age = age;
}
getDetails() {
return `${this._name} is ${this._age} years old.`;
}
setAge(newAge) {
if (newAge > 0) {
this._age = newAge;
}
}
}
const person = new Person("Afsar", 22);
console.log(person.getDetails()); // Afsar is 22 years old
person.setAge(25);
console.log(person.getDetails()); // Afsar is 25 years old
🔒 Here, the _age and _name are “private” (by convention), and access is controlled using getter/setter.
2️⃣ Abstraction — Focus on What, Not How
Definition: Abstraction hides unnecessary details and shows only the essential features of an object.
Example:
class Car {
startEngine() {
console.log("Starting engine...");
}
drive() {
this.startEngine();
console.log("Driving the car...");
}
}
const car = new Car();
car.drive();
🚗 The user doesn’t need to know how startEngine() works internally — just that calling drive() makes the car move.
3️⃣ Inheritance — Reuse the Code
Definition: Inheritance allows one class to inherit the properties and methods of another class.
Example:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog("Tommy");
dog.speak(); // Tommy barks.
4️⃣ Polymorphism — One Interface, Many Forms
Definition: Polymorphism allows objects to be treated as instances of their parent class, but with different behaviors.
Example:
class Shape {
area() {
return 0;
}
}
class Circle extends Shape {
constructor(radius) {
super();
this.radius = radius;
}
area() {
return Math.PI * this.radius ** 2;
}
}
class Rectangle extends Shape {
constructor(width, height) {
super();
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
const shapes = [new Circle(3), new Rectangle(4, 5)];
shapes.forEach(shape => {
console.log(shape.area());
});
🔄 Different shapes respond to the area() method in their own way.
🔚 Conclusion
The 4 pillars of OOP — Encapsulation, Abstraction, Inheritance, and Polymorphism — help us write clean, scalable, and maintainable code.
💡 Try implementing these concepts in your next project. The more you practice, the more natural OOP will become!