w3resource

TypeScript Animal Sounds - Abstract Classes and Inheritance

TypeScript Classes and OOP : Exercise-14 with Solution

Write a TypeScript exercise that defines an abstract class called Animal with properties like name and an abstract method makeSound(). Create derived classes (e.g., Tiger, Lion) that extend Animal and implement the makeSound() method with the unique sound each animal makes.

Sample Solution:

TypeScript Code:

// Define an abstract class 'Animal'
abstract class Animal {
  // Property
  name: string;

  // Constructor for Animal
  constructor(name: string) {
    this.name = name;
  }

  // Abstract method for making a sound
  abstract makeSound(): string;
}

// Define a derived class 'Tiger' extending 'Animal'
class Tiger extends Animal {
  // Implementation of makeSound for Tiger
  makeSound(): string {
    return "Roar! I'm a tiger.";
  }
}

// Define a derived class 'Lion' extending 'Animal'
class Lion extends Animal {
  // Implementation of makeSound for Lion
  makeSound(): string {
    return "Roar! I'm a lion.";
  }
}

// Create Tiger and Lion objects
const myTiger = new Tiger("Simba");
const myLion = new Lion("Mufasa");

// Call the makeSound method for each animal
console.log(`${myTiger.name}: ${myTiger.makeSound()}`); // Output: Simba: Roar! I'm a tiger.
console.log(`${myLion.name}: ${myLion.makeSound()}`);   // Output: Mufasa: Roar! I'm a lion.

Explanations:

In the exercise above -

  • First, define an abstract class "Animal" with a property 'name' and an abstract method "makeSound()" that represents the unique sound each animal makes.
  • Next, create derived classes 'Tiger' and 'Lion' that extend 'Animal'. Each derived class provides an implementation for the "makeSound()" method with specific sound descriptions.
  • Finally, create instances of 'Tiger' and 'Lion', and then call the "makeSound()" method for each animal to demonstrate the unique sounds they make.

Output:

"Simba: Roar! I'm a tiger."
"Mufasa: Roar! I'm a lion."

TypeScript Editor:

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


Previous: Shape Hierarchy in TypeScript - Abstract Classes and Inheritance.
Next: TypeScript Employee Hierarchy - 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.