Translate

Saturday 17 February 2024

What is Inheritance in Typescript ? 070

 What is Inheritance in Typescript ?


In TypeScript, inheritance allows you to create new classes (subclasses) that inherit properties and behaviors from existing classes (base classes). This promotes code reuse, reduces redundancy, and helps organize complex object hierarchies.

Key concepts:

  • Subclass: A class that inherits from another class (base class).

  • Base class: A class that provides the foundation for subclasses.

  • Inheritance: The mechanism by which a subclass acquires properties and methods from its base class.

  • extends keyword: Used to declare a subclass and specify its base class.

  • Method overriding: Subclasses can override inherited methods to provide their own implementation.

  • Protected members: Accessible within the class and its subclasses, not outside.

  • Super keyword: Used in subclasses to access inherited members from the base class.

Benefits of inheritance:

  • Code reuse: Subclasses inherit functionality from the base class, avoiding code duplication.

  • Polymorphism: Subclasses can exhibit different behavior while responding to the same method call (e.g., different animal sounds in an Animal class).

  • Organization: Inheritance helps structure complex object hierarchies, grouping related classes.

Example:


TypeScript

class Animal {
  protected name: string;

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

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

class Dog extends Animal {
  public bark(): void {
    console.log(`${this.name} barks!`);
  }
}

class Cat extends Animal {
  public meow(): void {
    console.log(`${this.name} meows!`);
  }
}

const dog = new Dog("Fido");
dog.move(); // Inherited from Animal
dog.bark(); // Specific to Dog

const cat = new Cat("Whiskers");
cat.move(); // Inherited from Animal
cat.meow(); // Specific to Cat

In this example:

  • Animal is the base class with a name property and a move method.

  • Dog and Cat are subclasses that inherit from Animal, gaining its properties and methods.

  • Both subclasses also have their own specific methods (bark and meow).

Remember:

  • Use inheritance judiciously for meaningful relationships between classes, avoiding excessive nesting.

  • Consider alternatives like composition or interfaces for situations where inheritance might not be the best fit.

  • Be mindful of potential issues like method overriding complexity and the diamond problem (multiple inheritance conflicts).

By understanding and effectively using inheritance in your TypeScript projects, you can create well-structured, reusable, and flexible code, facilitating maintainability and scalability.



No comments:

Post a Comment

Note: only a member of this blog may post a comment.