Typescript - Human Inheritance
Typescript Human Inheritance
Create class "Human" which has two protected members:
⚫ name[type as string] and age[type as number]
⚫ constructor(): this initialises name and age.
⚫ Create another class "Employee" which extends "Human" and have three members:
⚫ department[type as string], batch[type as string] and role[type as string]
⚫ constructor(): this initialises parent class protected members, department, batch and role.
⚫ getInfo(): this dispalys name, age, department, batch and role of the employee in a specific format.
Name: person one Age: 21 Department: computer science Batch: 2019 Role: Trainee
class Human {
protected name: string;
protected age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
class Employee extends Human {
private department: string;
private batch: string;
private role: string;
constructor(name: string, age: number, department: string, batch: string, role: string) {
super(name, age);
this.department = department;
this.batch = batch;
this.role = role;
}
getInfo(): void {
console.log(`Name: ${this.name}`);
console.log(`Age: ${this.age}`);
console.log(`Department: ${this.department}`);
console.log(`Batch: ${this.batch}`);
console.log(`Role: ${this.role}`);
}
}
// Example usage:
const employee = new Employee("person one", 21, "Computer Science", "2019", "Trainee");
employee.getInfo();
// Example usage:
const employee = new Employee("person one", 21, "Computer Science", "2019", "Trainee");
employee.getInfo();
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.