Day 20 Classes & OOP
Classes OOP ka core concept hai. Classes se reusable blueprints banate hain — jaise Car class se infinite cars bana sakte hain, har ek ki apni properties ke saath.
Class Basics
class keyword se class define karo, new se instance banao.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hi! I'm ${this.name}, ${this.age} years old.`;
}
birthday() {
this.age++;
return `Happy Birthday! Now ${this.age}`;
}
}
// Instances
let person1 = new Person("Zohaib", 25);
let person2 = new Person("Ali", 30);
console.log(person1.greet()); // Hi! I'm Zohaib, 25 years old.
console.log(person1.birthday()); // Happy Birthday! Now 26
Inheritance — extends
Ek class dusri class extend kar sakti hai.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // parent constructor call
this.breed = breed;
}
speak() {
return `${this.name} barks! Woof!`;
}
fetch(item) {
return `${this.name} fetched the ${item}!`;
}
}
let dog = new Dog("Rex", "German Shepherd");
console.log(dog.speak()); // Rex barks! Woof!
console.log(dog.fetch("ball")); // Rex fetched the ball!
🎯 Practice Challenge
BankAccount class banao: balance, deposit(), withdraw(), getBalance(). Overdraft allowed nahi hona chahiye.