🏠 Home / Hub

🟨 JS Lesson 10 — Inheritance & Polymorphism

← Back to JS Menu  |  🏠 Hub

1. extends — Class ကို Inherit လုပ်ခြင်း

Inheritance = Parent class ရဲ့ properties နဲ့ methods တွေကို Child class ရောက်အောင် ယူသုံးခြင်း
DRY (Don't Repeat Yourself) — shared code ကို parent ထဲတစ်ကြိမ်ပဲ ရေး
// Parent (Base) Class
class Animal {
  constructor(name, sound) {
    this.name  = name;
    this.sound = sound;
  }

  speak() {
    return `${this.name} says ${this.sound}!`;
  }

  eat(food) {
    return `${this.name} is eating ${food}.`;
  }
}

// Child (Derived) Class
class Dog extends Animal {
  constructor(name, breed) {
    super(name, "Woof");   // ← parent constructor ကို ခေါ်ရမယ် (REQUIRED)
    this.breed = breed;
  }

  fetch(item) {
    return `${this.name} fetches the ${item}! 🐕`;
  }
}

class Cat extends Animal {
  constructor(name, indoor) {
    super(name, "Meow");
    this.indoor = indoor;
  }

  purr() {
    return `${this.name} purrs... 😺`;
  }
}

const dog = new Dog("Rex", "Labrador");
const cat = new Cat("Mimi", true);

dog.speak();         // "Rex says Woof!"   ← inherited from Animal
dog.eat("bone");     // "Rex is eating bone."  ← inherited
dog.fetch("ball");   // "Rex fetches the ball! 🐕"  ← own method

cat.speak();         // "Mimi says Meow!"
cat.purr();          // "Mimi purrs... 😺"

2. Method Overriding

class Shape {
  constructor(color = "black") {
    this.color = color;
  }

  area() {
    return 0;   // base version — override ပါ
  }

  describe() {
    return `A ${this.color} shape with area ${this.area().toFixed(2)}`;
  }
}

class Circle extends Shape {
  constructor(radius, color) {
    super(color);
    this.radius = radius;
  }

  // Override parent's area()
  area() {
    return Math.PI * this.radius ** 2;
  }
}

class Rectangle extends Shape {
  constructor(w, h, color) {
    super(color);
    this.width = w;
    this.height = h;
  }

  area() {
    return this.width * this.height;
  }
}

class Triangle extends Shape {
  constructor(base, height, color) {
    super(color);
    this.base = base;
    this.height = height;
  }

  area() {
    return 0.5 * this.base * this.height;
  }
}

const c = new Circle(5, "red");
const r = new Rectangle(4, 6, "blue");
const t = new Triangle(3, 8, "green");

c.describe();  // "A red shape with area 78.54"
r.describe();  // "A blue shape with area 24.00"
t.describe();  // "A green shape with area 12.00"

3. Polymorphism — "Many Forms"

// Polymorphism = same interface, different behavior
// Array တစ်ခုထဲမှာ different types တွေ handle

class Animal {
  constructor(name) { this.name = name; }
  speak() { return `${this.name} makes a sound.`; }
}

class Dog extends Animal {
  speak() { return `${this.name} barks! 🐕`; }
}

class Cat extends Animal {
  speak() { return `${this.name} meows! 🐈`; }
}

class Duck extends Animal {
  speak() { return `${this.name} quacks! 🦆`; }
}

// Polymorphism in action — same loop, different outputs
const animals = [
  new Dog("Rex"),
  new Cat("Mimi"),
  new Duck("Donald"),
  new Dog("Buddy"),
];

animals.forEach(a => console.log(a.speak()));
// "Rex barks! 🐕"
// "Mimi meows! 🐈"
// "Donald quacks! 🦆"
// "Buddy barks! 🐕"

// isinstance check
console.log(animals[0] instanceof Dog);    // true
console.log(animals[0] instanceof Animal); // true (parent ပါ true)
console.log(animals[1] instanceof Dog);    // false

4. super() — Parent Method ခေါ်ခြင်း

class Vehicle {
  constructor(make, model, year) {
    this.make  = make;
    this.model = model;
    this.year  = year;
  }

  getInfo() {
    return `${this.year} ${this.make} ${this.model}`;
  }

  startEngine() {
    return "Engine started...";
  }
}

class ElectricCar extends Vehicle {
  constructor(make, model, year, range) {
    super(make, model, year);  // parent constructor
    this.range = range;
    this.battery = 100;
  }

  // super.method() — parent ကို EXTEND (replace မဟုတ်)
  getInfo() {
    return super.getInfo() + ` | Electric | Range: ${this.range}km`;
  }

  startEngine() {
    const parentMsg = super.startEngine();
    return `${parentMsg} ⚡ (Silent electric motor)`;
  }

  charge(amount) {
    this.battery = Math.min(100, this.battery + amount);
    return `Battery: ${this.battery}%`;
  }
}

const tesla = new ElectricCar("Tesla", "Model 3", 2024, 500);
tesla.getInfo();      // "2024 Tesla Model 3 | Electric | Range: 500km"
tesla.startEngine();  // "Engine started... ⚡ (Silent electric motor)"
tesla.charge(20);     // "Battery: 100%"

5. Multi-level Inheritance

// A → B → C (multi-level)

class LivingThing {
  constructor(name) { this.name = name; }
  breathe() { return `${this.name} breathes.`; }
}

class Animal extends LivingThing {
  constructor(name, legs) {
    super(name);
    this.legs = legs;
  }
  move() { return `${this.name} moves on ${this.legs} legs.`; }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name, 4);    // Animal's constructor
    this.breed = breed;
  }
  bark() { return `${this.name} (${this.breed}): WOOF!`; }
}

const rex = new Dog("Rex", "Husky");
rex.breathe();  // from LivingThing "Rex breathes."
rex.move();     // from Animal "Rex moves on 4 legs."
rex.bark();     // from Dog "Rex (Husky): WOOF!"

// Prototype chain:
// rex → Dog.prototype → Animal.prototype → LivingThing.prototype → Object.prototype

6. Live Demo — Polymorphism

📌 Inheritance Cheat Sheet

KeywordUsageDescription
extendsclass Dog extends AnimalInherit from parent
super()super(name, age)Call parent constructor (must be first)
super.method()super.greet()Call parent method from child
instanceofdog instanceof AnimalCheck inheritance chain
OverrideSame method name in childReplaces parent behavior

← JS 09  |  Next: JS 11 → Prototype Chain →

📌 Study Checklist