Object-Oriented Programming (OOP) is a programming paradigm that organizes code into reusable objects. It is widely used in modern software development due to its modularity, scalability, and ease of maintenance.
Key Concepts of OOP
Classes and Objects
A class is a blueprint for creating objects. An object is an instance of a class.
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
displayInfo() {
return `${this.brand} ${this.model}`;
}
}
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.displayInfo()); // Output: Toyota Corolla
Encapsulation
Encapsulation bundles data and methods within a single unit (class) and restricts direct access to some components.
class BankAccount {
#balance = 0; // Private property
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // Output: 100
Inheritance
Inheritance allows a class to inherit properties and methods from another class.
class Animal {
speak() {
console.log('Animal speaks');
}
}
class Dog extends Animal {
speak() {
console.log('Dog barks');
}
}
const myDog = new Dog();
myDog.speak(); // Output: Dog barks
Polymorphism
Polymorphism allows methods to perform differently based on the object that calls them.
class Shape {
area() {
return 0;
}
}
class Circle extends Shape {
constructor(radius) {
super();
this.radius = radius;
}
area() {
return Math.PI * this.radius ** 2;
}
}
const myCircle = new Circle(5);
console.log(myCircle.area()); // Output: 78.53981633974483
Why Learn OOP?
- Modularity: Breaks down complex problems into smaller, manageable pieces.
- Reusability: Promotes code reuse through inheritance and polymorphism.
- Maintainability: Makes code easier to maintain and debug.
Feel free to explore more about OOP and apply these concepts in your projects!