JavaScript Fundamentals / Classes

Method Overriding and Super

✅ Method Overriding

Method overriding happens when a child class (subclass) provides its own version of a method that already exists in the parent class (superclass).

Key points

  • Method names must be same in both classes

  • The child method replaces the parent method only for that class

  • Useful when child needs specialized behavior

  • Parent method is not deleted, just shadowed

Simple Example

class Animal {
  speak() {
    console.log("Animal makes a sound");
  }
}

class Dog extends Animal {
  speak() {
    console.log("Dog barks");
  }
}

const d = new Dog();
d.speak(); // Dog barks

✔ Dog overrides speak() from Animal

✔ Calling speak() uses the child version


✅ Why Do We Use Method Overriding?

  • To customize behavior in child classes

  • To add more specific functionality

  • To keep common logic in parent, variations in child

💡 Real-life example

  • Vehicle → start()

    • generic start mechanism

  • ElectricCar overrides start()

    • starts silently using battery

  • Truck overrides start()

    • engine ignition + warm-up


✅ super.method()

super allows the child class to access methods (or constructor) of the parent class.

  • When you want to extend the parent behavior, not completely replace it

  • To reuse parent logic and then add extra steps


Example Using super.speak()

class Animal {
  speak() {
    console.log("Animal makes a sound");
  }
}

class Dog extends Animal {
  speak() {
    super.speak(); // calls parent version
    console.log("Dog barks");
  }
}

const d = new Dog();
d.speak();
Animal makes a sound
Dog barks

✔ First runs parent method

✔ Then continues child behavior


✅ Important Notes

✔ Overriding ≠ Overloading (JS does not support method overloading natively)

✔ super.method() can only be used inside a class

✔ If child does not override, parent method is used automatically

✔ Arrow functions cannot be used as class methods for overriding (they don't go to prototype)