Low-level design2 min

Inheritance

Inheritance is the mechanism in Object-Oriented Programming (OOP) by which one class acquires the properties (fields) and behaviors (methods) of another class.

The class whose properties are inherited is called the Superclass (or Parent/Base class), and the class that inherits those properties is called the Subclass (or Child/Derived class).

Real-Life Analogy

Think of biological inheritance. A Child inherits traits (like eye color or height) from their Parents.

In the real world of objects, think of a Vehicle. A Vehicle has wheels, an engine, and the ability to move.

  • A Car is a Vehicle. It inherits those base properties but adds its own (like doors and AC).
  • A Motorcycle is a Vehicle. It inherits the base properties but adds its own (like handlebars and a kickstand).

Inheritance establishes an "IS-A" relationship.

How to Implement Inheritance

In most OOP languages, inheritance is implemented using a keyword like extends or :.

Example in Code

typescript
// Base Class (Superclass)
class Animal {
  protected name: string;

  constructor(name: string) {
    this.name = name;
  }

  public eat(): void {
    console.log(`${this.name} is eating.`);
  }

  public sleep(): void {
    console.log(`${this.name} is sleeping.`);
  }
}

// Derived Class (Subclass)
class Dog extends Animal {
  private breed: string;

  constructor(name: string, breed: string) {
    super(name); // Calls the parent constructor
    this.breed = breed;
  }

  public bark(): void {
    console.log(`${this.name} (a ${this.breed}) barks: Woof!`);
  }
}

// Usage
const myDog = new Dog("Buddy", "Golden Retriever");
myDog.eat();   // Inherited from Animal
myDog.sleep(); // Inherited from Animal
myDog.bark();  // Specific to Dog

Why is it Important?

  • Code Reusability: You can write common code once in the superclass and reuse it across multiple subclasses, adhering to the DRY (Don't Repeat Yourself) principle.
  • Method Overriding: Subclasses can provide their own specific implementation of a method that is already defined in the superclass (which ties into Polymorphism).

The "Composition over Inheritance" Principle

While inheritance is powerful, modern software design often favors Composition over Inheritance. Deep inheritance hierarchies (e.g., Dog extends Mammal extends Animal extends Organism) can become rigid and difficult to maintain. If a class needs functionality from multiple sources, it is often better to compose it by injecting dependencies rather than inheriting them.