TypeScript Method Overriding
TypeScript Classes and OOP : Exercise-11 with Solution
Write a TypeScript program that creates a class called Shape with properties color and a method draw(). This program prints a message indicating that the shape is being drawn. Then, create a derived class Circle that extends Shape. Override the draw() method in the Circle class to provide a specific implementation for drawing a circle.
Sample Solution:
TypeScript Code:
// Define the base class 'Shape'
class Shape {
// Property
color: string;
// Constructor for Shape
constructor(color: string) {
this.color = color;
}
// Method to draw (base implementation)
draw() {
console.log(`Drawing a ${this.color} shape.`);
}
}
// Define the derived class 'Circle' extending 'Shape'
class Circle extends Shape {
// Constructor for Circle
constructor(color: string) {
// Call the constructor of the base class 'Shape'
super(color);
}
// Override the draw method for Circle
draw() {
console.log(`Drawing a ${this.color} circle.`);
}
}
// Create a Circle object
const myCircle = new Circle("Red");
// Call the draw method for Circle
myCircle.draw(); // Output: Drawing a Red circle.
Explanations:
In the exercise above -
- First, we define the base class "Shape" with a property 'color' and a constructor that initializes the 'color' property when a 'Shape' object is created.
- The "Shape" class also includes a "draw()" method, which provides a base implementation for drawing a shape and prints a message indicating the color of the shape.
- We define the derived class "Circle" that extends "Shape". The "Circle" class has its own constructor that calls the constructor of the base class "Shape" to initialize the 'color' property.
- The "Circle" class overrides the "draw()" method to provide a specific implementation for drawing a circle. It prints a message indicating the color of the circle.
- We create an instance of the "Circle" class called 'myCircle' and call the "draw()" method on it to demonstrate the overridden behavior.
When we run this TypeScript code, it will create a 'Circle' object, call the overridden "draw()" method, and display the specific drawing message for a circle in the console.
Output:
"Drawing a Red circle."
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript Inheritance with Constructor Overriding.
Next: TypeScript Multi-Level Inheritance.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/typescript-exercises/typescript-class-and-oop-exercise-11.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics