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!
Top comments (0)