TypeScript Inheritance with Constructor Overriding
TypeScript Classes and OOP : Exercise-10 with Solution
Write a TypeScript class called Person with properties name and age. Implement a constructor that initializes these properties when a Person object is created. Then, create a derived class Employee that extends Person. Override the constructor of the Employee class to include an additional property employeeId.
Sample Solution:
TypeScript Code:
// Define the base class 'Person'
class Person {
// Properties
name: string;
age: number;
// Constructor for Person
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
// Define the derived class 'Employee' extending 'Person'
class Employee extends Person {
// Additional property for Employee
employeeId: string;
// Constructor for Employee (override)
constructor(name: string, age: number, employeeId: string) {
// Call the constructor of the base class 'Person'
super(name, age);
// Initialize the 'employeeId' property
this.employeeId = employeeId;
}
}
// Create an Employee object
const myEmployee = new Employee("Elmira Ugochi", 40, "EPM-0012");
// Access and print the properties
console.log("Name:", myEmployee.name);
console.log("Age:", myEmployee.age);
console.log("Employee ID:", myEmployee.employeeId);
Explanations:
In the exercise above -
- First, we define the base class "Person" with the properties 'name' and 'age'. The constructor for the "Person" class initializes these properties when a "Person" object is created.
- Next, we define the derived class "Employee" that extends "Person". The "Employee" class adds an additional property 'employeeId'.
- The constructor for the "Employee" class overrides the base class constructor to include the 'employeeId' property. It calls the constructor of the base class "Person" using super(name, age) to initialize the inherited properties.
- Finally, we create an instance of the "Employee" class called 'myEmployee', and we access and print the properties of the 'myEmployee' object to verify that they have been initialized correctly, including the 'employeeId' property.
When we run the code, it will create an 'Employee' object with the specified properties and display their values in the console.
Output:
"Name:" "Elmira Ugochi" "Age:" 40 "Employee ID:" "EPM-0012"
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript Basic Inheritance.
Next: TypeScript Method Overriding.
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-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics