TypeScript Course
TypeScript
/
Advanced

Inheritance & Abstract Classes

Definition

Inheritance (`extends`) allows a class to copy the behavior of another class. Abstract classes are special base classes that cannot be instantiated directly; they exist purely as blueprints for child classes to inherit from.

Explain Like I'm New

An Abstract Class is a concept, like a 'Vehicle'. You cannot go to a dealership and say 'I would like to buy 1 Vehicle please'. You must buy a specific implementation: a Car, or a Truck. The Abstract 'Vehicle' class enforces that ALL child vehicles MUST have an engine, but forces the child to define exactly HOW the engine works.

Real World Example

Creating an abstract `DatabaseAdapter` class that requires a `connect()` method. You then build child classes `MySQLAdapter` and `MongoAdapter` that implement the specific connection logic.

Common Use Cases

  • •Polymorphism
  • •Enforcing strict architectural contracts across multiple classes

Interactive Example

abstract class Employee {
  constructor(public name: string) {}

  // Concrete method (Shared by all children)
  printName() {
    console.log("Employee: " + this.name);
  }

  // Abstract method (Children MUST provide the implementation)
  abstract calculateSalary(): number;
}

// const e = new Employee("Alice"); // ERROR: Cannot create instance of abstract class.

class FullTimeEmployee extends Employee {
  // Required by parent contract!
  calculateSalary() {
    return 60000;
  }
}

const bob = new FullTimeEmployee("Bob");
bob.printName(); // "Employee: Bob" (Inherited)
console.log(bob.calculateSalary()); // 60000 (Implemented)

Interview Questions

basic

  • Can you instantiate an abstract class using `new`?

intermediate

  • What is an abstract method?

advanced

  • What is the difference between an Interface and an Abstract Class?

Flash Cards

Question

What is an abstract method?

Click to reveal answer
Answer

It is a method defined in an abstract class that has a signature, but NO body (e.g., `abstract getSalary(): number;`). Any class that extends this parent is strictly FORCED to implement the body of that method.

Question

Interface vs Abstract Class?

Click to reveal answer
Answer

An Interface ONLY contains types; it disappears completely at runtime. An Abstract Class can contain full JavaScript logic (like a base `log()` method) alongside abstract requirements, and it remains in the compiled code as a normal JS class.