TypeScript Basic Inheritance
TypeScript Classes and OOP : Exercise-9 with Solution
Write a TypeScript class called Animal with properties name and species. Implement a constructor that initializes these properties when an Animal object is created. Next, create a derived class Tiger that extends Animal. Add a method roar() to the Tiger class that prints a message indicating that the tiger is roaring.
Sample Solution:
TypeScript Code:
// Define the base class 'Animal'
class Animal {
// Properties
name: string;
species: string;
// Constructor for Animal
constructor(name: string, species: string) {
this.name = name;
this.species = species;
}
}
// Define the derived class 'Tiger' extending 'Animal'
class Tiger extends Animal {
// Method to roar
roar() {
console.log(`The tiger named ${this.name} is roaring.`);
}
}
// Create a Tiger object
const myTiger = new Tiger("Saber", "Bengal Tiger");
// Access and call the roar method
myTiger.roar(); // Output: The tiger named Saber is roaring.
Explanations:
In the exercise above -
- First, we define the base class "Animal" with the properties 'name' and 'species'. The constructor for the "Animal" class initializes these properties when an "Animal" object is created.
- Next we define the derived class "Tiger" that extends "Animal". The "Tiger" class includes a method "roar()" that uses the properties from the base class to print a message indicating that the tiger is roaring.
- Finally, we create an instance of the "Tiger" class called "myTiger" and call the "roar()" method, and display the roaring message in the console.
Output:
"The tiger named Saber is roaring."
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript Constructor Initialization.
Next: TypeScript Inheritance with Constructor Overriding.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics