w3resource

TypeScript Multi-Level Inheritance

TypeScript Classes and OOP : Exercise-12 with Solution

Write a TypeScript program that defines a class called Vehicle with properties make and model. Implement a constructor that initializes these properties when a Vehicle object is created. Then, create a derived class Car that extends Vehicle. Finally, create a derived class SportsCar that extends Car. Ensure that properties are inherited correctly and each class has its own constructor.

Sample Solution:

TypeScript Code:

// Define the base class 'Vehicle'
class Vehicle {
  // Properties
  make: string;
  model: string;

  // Constructor for Vehicle
  constructor(make: string, model: string) {
    this.make = make;
    this.model = model;
  }
}

// Define the derived class 'Car' extending 'Vehicle'
class Car extends Vehicle {
  // Constructor for Car
  constructor(make: string, model: string) {
    // Call the constructor of the base class 'Vehicle'
    super(make, model);
  }
}

// Define the further derived class 'SportsCar' extending 'Car'
class SportsCar extends Car {
  // Constructor for SportsCar
  constructor(make: string, model: string) {
    // Call the constructor of the base class 'Car'
    super(make, model);
  }
}

// Create a SportsCar object
const mySportsCar = new SportsCar("Lamborghini", "Aventador");

// Access and print the properties
console.log("Make:", mySportsCar.make);   
console.log("Model:", mySportsCar.model);

Explanations:

In the exercise above -

  • First, define the base class "Vehicle" with properties 'make' and 'model'. The constructor for the "Vehicle" class initializes these properties when a 'Vehicle' object is created.
  • Define the derived class "Car" that extends "Vehicle". The "Car" class has its own constructor that calls the constructor of the base class "Vehicle" using super(make, model) to initialize the inherited properties.
  • Define the further derived class "SportsCar" that extends "Car". The "SportsCar" class also has its own constructor that calls the constructor of the base class "Car" using super(make, model) to initialize the properties inherited from both "Car" and "Vehicle".
  • Create an instance of the "SportsCar" class called mySportsCar, and we access and print the properties of the 'mySportsCar' object to verify that they have been inherited and initialized correctly.

When we run this TypeScript code, it will create a 'SportsCar' object with the specified properties and display their values in the console.

Output:

"Make:" "Lamborghini"
"Model:" "Aventador"

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: TypeScript Method Overriding.
Next: Shape Hierarchy in TypeScript - Abstract Classes and Inheritance.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.