JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Class Inheritance


Inheritance is a fundamental concept in object-oriented programming that allows one class to acquire the properties and methods of another class. In JavaScript, class inheritance enables developers to create hierarchical relationships between classes, promoting code reusability, modularity, and maintainability. By leveraging inheritance, you can extend existing functionality without duplicating code and implement structured, scalable applications.

In this tutorial, you will learn about JavaScript class inheritance, how to implement it using extends and super, practical examples, common mistakes, best practices, and real-world applications.

Why Class Inheritance Is Important

Class inheritance is important because it allows you to:

  • Reuse existing code efficiently

  • Build hierarchical relationships between classes

  • Extend functionality without modifying the original class

  • Maintain clean and organized code

  • Support polymorphism and object-oriented design patterns

Without inheritance, you would have to manually duplicate methods and properties, leading to repetitive and error-prone code.

The Basics of Class Inheritance

In JavaScript, inheritance is implemented using the extends keyword. A class that extends another class is called a subclass or derived class, while the class being extended is called a superclass or base class.

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    greet() {
        console.log("Hello, my name is " + this.name);
    }
}

class Student extends Person {
    constructor(name, age, course) {
        super(name, age); // Calls the constructor of the superclass
        this.course = course;
    }

    study() {
        console.log(this.name + " is studying " + this.course);
    }
}

const student = new Student("Aarushi", 20, "JavaScript");
student.greet(); // Hello, my name is Aarushi
student.study(); // Aarushi is studying JavaScript

In this example:

  • Student inherits from Person

  • The super() function calls the constructor of the parent class to initialize inherited properties

  • The Student class adds its own property course and method study()

Using super in Subclasses

The super keyword is essential in subclasses. It can be used to:

  • Call the parent class constructor

  • Access or invoke parent class methods

Example: Accessing Parent Methods

class Teacher extends Person {
    constructor(name, age, subject) {
        super(name, age);
        this.subject = subject;
    }

    greet() {
        super.greet(); // Calls the parent class greet method
        console.log("I teach " + this.subject);
    }
}

const teacher = new Teacher("Saanvi", 30, "Math");
teacher.greet();
// Hello, my name is Saanvi
// I teach Math

Here, the greet method in the subclass calls the parent class greet method using super.greet() and then adds additional behavior.

Overriding Methods

Subclasses can override methods from the parent class to provide customized behavior:

class Person {
    greet() {
        console.log("Hello from Person");
    }
}

class Student extends Person {
    greet() {
        console.log("Hello from Student");
    }
}

const student = new Student();
student.greet(); // Hello from Student

Method overriding is useful when a subclass needs to change or extend the functionality of a parent method.

Inheritance Chains

JavaScript supports multiple levels of inheritance. A class can extend another class, which itself extends another class, forming an inheritance chain:

class Person {
    constructor(name) {
        this.name = name;
    }

    greet() {
        console.log("Hello, my name is " + this.name);
    }
}

class Teacher extends Person {
    constructor(name, subject) {
        super(name);
        this.subject = subject;
    }

    teach() {
        console.log(this.name + " teaches " + this.subject);
    }
}

class HeadTeacher extends Teacher {
    constructor(name, subject, department) {
        super(name, subject);
        this.department = department;
    }

    manage() {
        console.log(this.name + " manages the " + this.department + " department");
    }
}

const headTeacher = new HeadTeacher("Priya", "Science", "STEM");
headTeacher.greet();  // Hello, my name is Priya
headTeacher.teach();  // Priya teaches Science
headTeacher.manage(); // Priya manages the STEM department

This demonstrates how properties and methods can be inherited through multiple levels, allowing structured and hierarchical class designs.

Common Mistakes

  • Forgetting to call super() in a subclass constructor, leading to errors

  • Overriding methods without intending to, which may break inherited functionality

  • Using super incorrectly outside of a subclass context

  • Attempting multiple inheritance directly (JavaScript only supports single inheritance; mixins are an alternative)

  • Assuming inherited methods are private—they are public by default unless explicitly made private

Best Practices

  • Use extends only when there is a clear “is-a” relationship between classes

  • Always call super() in the subclass constructor before accessing this

  • Use method overriding judiciously to extend behavior without breaking the parent class

  • Consider using private fields (#field) and methods to encapsulate subclass-specific data

  • Keep inheritance hierarchies shallow to maintain readability and avoid complexity

Real-World Applications

  • Modeling organizational structures such as employees, managers, and executives

  • Creating UI component hierarchies in frontend frameworks like React

  • Extending utility or library classes to add custom behavior

  • Building game entities where characters inherit from a base entity class

  • Implementing reusable data models in backend applications

Practical Examples

Example 1: Basic Subclass

class Person {
    constructor(name) {
        this.name = name;
    }

    greet() {
        console.log("Hello, my name is " + this.name);
    }
}

class Student extends Person {
    constructor(name, course) {
        super(name);
        this.course = course;
    }

    study() {
        console.log(this.name + " is studying " + this.course);
    }
}

const student = new Student("Aarushi", "JavaScript");
student.greet(); // Hello, my name is Aarushi
student.study(); // Aarushi is studying JavaScript

Example 2: Overriding Parent Methods

class Teacher extends Person {
    greet() {
        console.log("Hello, I am a teacher named " + this.name);
    }
}

const teacher = new Teacher("Saanvi");
teacher.greet(); // Hello, I am a teacher named Saanvi

Example 3: Multi-Level Inheritance

class HeadTeacher extends Teacher {
    constructor(name, department) {
        super(name);
        this.department = department;
    }

    manage() {
        console.log(this.name + " manages the " + this.department + " department");
    }
}

const headTeacher = new HeadTeacher("Priya", "Science");
headTeacher.greet();  // Hello, I am a teacher named Priya
headTeacher.manage(); // Priya manages the Science department

Summary of JavaScript Class Inheritance

JavaScript class inheritance allows developers to create hierarchical relationships between classes, promoting code reuse and maintainability. Using extends and super, subclasses can inherit properties and methods, override them, and add additional functionality. Proper understanding of inheritance helps in building structured, modular, and scalable applications while adhering to object-oriented programming principles. By following best practices and avoiding common mistakes, you can leverage class inheritance effectively in professional JavaScript development.


Practice Questions

  1. Basic Inheritance
    Create a class Animal with a property name and a method speak(). Extend it with a class Dog that overrides speak() to print a custom message. Create an instance and call the method.

  2. Calling Parent Constructor
    Create a parent class Vehicle with brand and model. Extend it with a class Car and use super() to initialize the parent properties. Log all properties of an instance.

  3. Method Overriding
    Create a class Shape with a method area() that returns 0. Extend it with Rectangle and Circle, and override area() to compute actual areas.

  4. Multi-level Inheritance
    Create a class hierarchy: EmployeeManagerDirector. Each level should add new properties and methods. Instantiate a Director and call all inherited and own methods.

  5. Static Methods in Inheritance
    Create a class MathUtil with a static method square(). Extend it with AdvancedMath and call square() from the child class.

  6. Overriding Parent Methods with super
    Create a parent class Person with greet(). Extend it with Student and override greet() but also call super.greet(). Instantiate and test the method.

  7. Inheritance with Multiple Instances
    Create a parent class Animal and a child class Cat. Instantiate multiple cats and demonstrate that each has inherited methods without duplicating them in memory.

  8. Adding Child-specific Methods
    Extend a class Vehicle with Bike and add a method ride(). Call both inherited and child-specific methods from an instance.

  9. Overriding Constructor Properties
    Create a parent class Device with brand. Extend it with Phone and override the constructor to add model. Ensure parent properties are initialized correctly using super().

  10. Dynamic Method Calls in Child
    Create a child class that overrides a parent method and calls it dynamically based on a condition (e.g., if type === "special" call super method). Test with different conditions.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top