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 (OOP) that allows one class to extend another class, inheriting its properties and methods. In JavaScript, class inheritance is built on prototypes, but ES6 introduced the class syntax with the extends keyword, making inheritance more intuitive and readable.

Class inheritance allows developers to reuse code, avoid duplication, and create hierarchical relationships between objects. It’s essential for building scalable and maintainable applications, especially in frameworks like React, Node.js, and Angular.

1. What is Class Inheritance?

Class inheritance allows a child (subclass) to inherit features from a parent (superclass).

  • The child class can access properties and methods of the parent class.

  • The child class can also override methods for custom behavior.

  • Use extends to create a subclass.

  • Use super() to call the parent constructor.

2. Basic Example of Class Inheritance

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

  speak() {
    console.log(`${this.name} makes a sound`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // Call parent constructor
    this.breed = breed;
  }

  speak() {
    console.log(`${this.name} barks`);
  }
}

const dog1 = new Dog("Rex", "Labrador");
dog1.speak(); // Rex barks
console.log(dog1.breed); // Labrador
  • Dog inherits from Animal using extends.

  • super(name) calls the parent constructor to initialize inherited properties.

  • The speak() method in Dog overrides the parent method.

3. Method Overriding

Child classes can override parent methods to provide custom behavior:

class Cat extends Animal {
  speak() {
    console.log(`${this.name} meows`);
  }
}

const cat1 = new Cat("Whiskers");
cat1.speak(); // Whiskers meows
  • Method overriding allows polymorphism, a key OOP principle.

  • You can still call the parent method using super.methodName() if needed.

class Bird extends Animal {
  speak() {
    super.speak(); // Call parent method
    console.log(`${this.name} chirps`);
  }
}

const bird1 = new Bird("Tweety");
bird1.speak();
// Tweety makes a sound
// Tweety chirps

4. Inheriting Properties

Child classes automatically inherit instance properties defined in the parent class, reducing duplication:

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

  info() {
    return `${this.brand} ${this.model}`;
  }
}

class Car extends Vehicle {
  constructor(brand, model, doors) {
    super(brand, model); // Parent properties
    this.doors = doors;
  }

  carInfo() {
    return `${this.info()}, Doors: ${this.doors}`;
  }
}

const car1 = new Car("Toyota", "Camry", 4);
console.log(car1.carInfo()); // Toyota Camry, Doors: 4
  • super(brand, model) initializes parent properties.

  • car1 can access both parent methods and child-specific methods.

5. Multiple Levels of Inheritance

JavaScript allows multi-level inheritance, where a subclass extends a parent, and another subclass extends that subclass:

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

  work() {
    console.log(`${this.name} is working`);
  }
}

class Manager extends Employee {
  constructor(name, department) {
    super(name);
    this.department = department;
  }

  manage() {
    console.log(`${this.name} manages ${this.department} department`);
  }
}

class Director extends Manager {
  constructor(name, department, level) {
    super(name, department);
    this.level = level;
  }

  directorInfo() {
    console.log(`${this.name}, Level: ${this.level}, Department: ${this.department}`);
  }
}

const director1 = new Director("Alice", "Sales", "Senior");
director1.work();         // Alice is working
director1.manage();       // Alice manages Sales department
director1.directorInfo(); // Alice, Level: Senior, Department: Sales
  • Multi-level inheritance allows building complex hierarchies.

  • Each level can add new properties or override methods.

6. Static Methods and Inheritance

Static methods can also be inherited by child classes:

class MathUtil {
  static square(x) {
    return x * x;
  }
}

class AdvancedMath extends MathUtil {}

console.log(AdvancedMath.square(5)); // 25
  • Static methods belong to the class itself, not instances.

  • Child classes inherit static methods automatically.

7. Notes and Best Practices

  1. Use extends for clean inheritance instead of manually modifying prototypes.

  2. Always call super() in a child constructor before using this.

  3. Use method overriding carefully to maintain expected behavior.

  4. Avoid deep inheritance hierarchies; prefer composition over inheritance in complex systems.

  5. Use static methods for utility functions that don’t require instance data.

  6. Keep constructors simple; avoid performing heavy computations inside them.

8. Summary of the Tutorial

  • Class inheritance allows a child class to inherit properties and methods from a parent class.

  • The extends keyword creates the inheritance relationship.

  • super() is used to call the parent constructor and optionally parent methods.

  • Methods in child classes can override parent methods for custom behavior.

  • Multi-level inheritance and static methods provide flexibility for complex applications.

  • Mastering inheritance enables code reuse, organization, and scalability in JavaScript applications.

Understanding class inheritance is essential for building professional-level JavaScript applications, structuring code effectively, and working with modern frameworks.


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.


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