Home
Module 3
Pillar 2 of OOP

Inheritance

الوراثة - الكلاسات بتورث بعضها

👨‍👩‍👧‍👦إيه هي الوراثة Inheritance؟

👪 تشبيه العيلة

الوراثة في البرمجة زي الوراثة في الحياة:

  • • الابن بـيورث صفات من الأب (لون العين، الطول)
  • • بس ممكن يكون عنده صفات إضافية خاصة بيه
  • • أو يـغير سلوك موروث (override)

✅ ليه الوراثة مهمة؟

  • Code Reuse - متكررش نفس الكود
  • Hierarchy - تنظيم الكلاسات
  • Extensibility - سهولة التوسع

📌 المصطلحات

  • Parent/Base/Super - الكلاس الأب
  • Child/Derived/Sub - الكلاس الابن
  • extends - "بيورث من"

🌳 شجرة الوراثة

Animal🐾 Parent Class🐕 Dogextends Animal🐈 Catextends Animal🐦 Birdextends AnimalInherited from Animal:name, age, eat(), sleep()
💡 كل الأولاد (Dog, Cat, Bird) بيورثوا الـ properties والـ methods من Animal

📦extends & super

animals.ts
// Parent Class (الأب)
class Animal {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  eat(): string {
    return `${this.name} is eating 🍽️`;
  }

  sleep(): string {
    return `${this.name} is sleeping 😴`;
  }
}

// Child Class (الابن)
class Dog extends Animal {
  breed: string;  // خاصية جديدة

  constructor(name: string, age: number, breed: string) {
    super(name, age);  // نادي الأب!
    this.breed = breed;
  }

  // Method جديدة
  bark(): string {
    return `${this.name} says: Woof! 🐕`;
  }

  // Override - تغيير سلوك
  eat(): string {
    return `${this.name} eats dog food 🦴`;
  }
}

const buddy = new Dog("Buddy", 3, "Golden");
console.log(buddy.eat());   // Buddy eats dog food
console.log(buddy.sleep()); // Buddy is sleeping (inherited!)
console.log(buddy.bark());  // Buddy says: Woof!

🔍 شرح كل جزء:

👴 الكلاس الأب Animal

فيه الـ properties الأساسية (name, age) والـ methods المشتركة (eat(), sleep())

🔗 extends - الوصلة

Dog extends Animal يعني Dog بيورث كل حاجة من Animal تلقائياً!

📞 super() - نادي أبوك

لازم تنادي super() في الـ constructor عشان تمرر البيانات للـ Parent

✨ حاجات جديدة

الـ Dog عنده breed و bark() - إضافات مش موجودة في Animal

🔄 Override - غير السلوك

الـ Dog عمل eat() بتاعته - بدل "is eating" بقت "eats dog food"!

🎮جرب بنفسك - الوراثة في الحيوانات

اختار الحيوان:

Code:

const animal = new Dog("Max", 3);

النتيجة:

⬇️ موروث من Animal:

eat() → "Max is eating 🍽️"

sleep() → "Max is sleeping 😴"

✨ خاص بـ Dog:

makeSound() → "وو وو! 🐕"

move() → "بيجري على 4 رجول"

🐕

📝 ملخص Inheritance

👨‍👩‍👧

extends

الكلمة اللي بنورث بيها

📞

super()

استدعاء الـ Parent

🔄

Override

تغيير السلوك الموروث

♻️

Code Reuse

متكررش الكود