OOP (Object-Oriented Programming) is a programming paradigm where programs are designed using objects — which can hold data (properties) and methods (functions).
A Class is a blueprint to create objects with predefined properties and methods.
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
displayInfo() {
return `Car: ${this.brand} ${this.model}`;
}
}
An Object is an instance of a Class. It holds actual values for the properties defined by the class.
const car1 = new Car('Toyota', 'Corolla');
console.log(car1.displayInfo()); // Output: Car: Toyota Corolla
Encapsulation hides internal details and exposes only necessary parts.
class BankAccount {
#balance = 0; // private field
deposit(amount) {
if(amount > 0) this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const acc = new BankAccount();
acc.deposit(1000);
console.log(acc.getBalance()); // Output: 1000
Inheritance allows a class to acquire properties and methods from another class.
class Vehicle {
move() {
return 'Moving...';
}
}
class Bike extends Vehicle {
ringBell() {
return 'Ring Ring!';
}
}
const myBike = new Bike();
console.log(myBike.move()); // Moving...
console.log(myBike.ringBell()); // Ring Ring!
Polymorphism allows objects to be treated as instances of their parent class while still calling their own methods.
class Animal {
speak() {
return 'Some sound';
}
}
class Dog extends Animal {
speak() {
return 'Bark';
}
}
const pet = new Dog();
console.log(pet.speak()); // Bark