Your Page Title
🔍

    📘 JavaScript Class Inheritance

    Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to derive properties and methods from another class, promoting code reuse and logical structure.

    What is Class Inheritance?

    In JavaScript, class inheritance means creating a new class (called a subclass or child class) based on an existing class (called a superclass or parent class). The subclass inherits all properties and methods from the superclass, and can also add its own.


    Why Use Inheritance?

    • Reuse code: Avoid rewriting common functionality.
    • Extend behavior: Add or modify features specific to subclasses.
    • Organize code: Reflect real-world relationships (e.g., Animals → Dogs).

    Basic Syntax of Inheritance

    You use the extends keyword to set up inheritance and super() to call the parent class constructor.

    jsCopyEditclass Animal {
      constructor(name) {
        this.name = name;
      }
    
      speak() {
        console.log(`${this.name} makes a sound.`);
      }
    }
    
    class Dog extends Animal {
      constructor(name, breed) {
        super(name);  // Call the parent constructor to initialize name
        this.breed = breed;
      }
    
      speak() {
        console.log(`${this.name} barks.`);
      }
    
      info() {
        console.log(`${this.name} is a ${this.breed}`);
      }
    }
    
    const dog = new Dog("Buddy", "Golden Retriever");
    dog.speak();  // Buddy barks.
    dog.info();   // Buddy is a Golden Retriever
    

    How It Works:

    • Dog class extends Animal class.
    • super(name) calls the Animal constructor so name gets set correctly.
    • Dog overrides the speak() method to provide a more specific behavior.
    • Dog adds a new method info() unique to itself.

    Important Points about super()

    • super() must be called in the constructor of a subclass before accessing this.
    • It invokes the constructor of the parent class.
    • You can also call parent methods using super.methodName():
    jsCopyEditclass Cat extends Animal {
      speak() {
        super.speak(); // Calls Animal's speak()
        console.log(`${this.name} meows.`);
      }
    }
    
    const cat = new Cat("Whiskers");
    cat.speak();
    // Output:
    // Whiskers makes a sound.
    // Whiskers meows.
    

    Inheritance of Properties and Methods

    • Subclasses inherit all public properties and methods of the superclass.
    • You can override methods in the subclass for customized behavior.
    • Subclasses can add new properties or methods unique to them.

    Extending Built-in Classes

    JavaScript allows you to extend built-in classes like Array, Error, or Date:

    jsCopyEditclass MyArray extends Array {
      first() {
        return this[0];
      }
    }
    
    const arr = new MyArray(10, 20, 30);
    console.log(arr.first()); // 10
    

    When to Use Inheritance?

    • When classes have an “is-a” relationship (Dog is an Animal).
    • To share common behavior and structure among related classes.
    • To override and extend functionality without rewriting code.

    Common Pitfalls

    • Don’t overuse inheritance — prefer composition when appropriate.
    • Always call super() in subclass constructors.
    • Avoid deep inheritance chains, which make code complex.

    Summary Table

    ConceptDescription
    extendsKeyword to inherit from a parent class
    super()Calls the parent class constructor
    Method overridingRedefining a method in the subclass
    super.method()Calls a parent method from a subclass
    SubclassThe class inheriting from another (child)
    SuperclassThe base class being inherited from (parent)

    Practice Challenge

    1. Create a Vehicle class with properties like make and year and method start().
    2. Create a subclass Car that extends Vehicle, adding a property doors and overriding start() with a more specific message.
    3. Instantiate a Car and test its methods.

    Inheritance in JavaScript classes is a powerful way to build scalable, reusable code that models real-world relationships elegantly. Understanding extends and super() unlocks advanced object-oriented patterns in your applications.