TypeScript Derived Class Constructor
TypeScript Classes and OOP : Exercise-7 with Solution
Write a TypeScript class called Shape with properties like color. Implement a constructor that initializes the color property when a Shape object is created. Then, create a derived class Circle that extends Shape. Implement a constructor for the Circle class that takes color and radius as parameters and initializes them along with the color property of the base class.
Sample Solution:
TypeScript Code:
class Shape {
// Property
color: string;
// Constructor for Shape
constructor(color: string) {
this.color = color;
}
}
// Derived class 'Circle' extends 'Shape'
class Circle extends Shape {
// Additional property for Circle
radius: number;
// Constructor for Circle
constructor(color: string, radius: number) {
// Call the constructor of the base class 'Shape'
super(color);
// Initialize the 'radius' property
this.radius = radius;
}
}
// Create a Circle object
const myCircle = new Circle("Black", 7);
// Access and print the properties
console.log("Color:", myCircle.color); // Output: Color: Black
console.log("Radius:", myCircle.radius); // Output: Radius: 7
Explanations:
In the exercise above -
- First, we define a base class "Shape" with a property 'color'.
- The constructor for the "Shape" class takes a parameter 'color' and initializes the 'color' property.
- We create a derived class "Circle" that extends "Shape" and adds an additional property 'radius'.
- The constructor for the "Circle" class takes parameters 'color' and 'radius'. It first calls the constructor of the base class "Shape" using super(color) to initialize the 'color' property of the base class. Then, it initializes the 'radius' property with the provided value.
- Finally, we create an instance of the "Circle" class called 'myCircle', and we access and print the properties of the 'myCircle' object to verify that they have been initialized correctly.
Output:
"Color:" "Black" "Radius:" 7
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript Constructor Overloading.
Next: TypeScript Constructor Initialization.
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-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics