TYPESCRIPT
TypeScript - Inheritance
Create a class "Human" which has two protected members:
- name [type as string] and age [type as number]
- constructor(): this initializes name and age
- Create another class "Employee" which extends "Human" and have three members:
- department (string), batch (string) and role (string)
- constructor(): this initializes parent class protected members, department, batch and role.
- getInfo(): this displays name, age, department, batch and role of the employee in a specific format.
Sample Output:
Name: person one
Age: 21
Department: computer science
Batch: 2019
Role: Trainee
Solution:
class Human {
protected name: string;
protected age: number;
constructor(theName: string, theAge: number) {
this.name = theName;
this.age = theAge;
}
}
class Employee1 extends Human {
department: string;
batch: string;
role: string;
constructor(
name: string,
age: number,
theDepartment: string,
theBatch: string,
theRole: string
) {
super(name, age);
this.department = theDepartment;
this.batch = theBatch;
this.role = theRole;
}
getInfo() {
console.log(
"Name: " +
this.name +
"\nAge: " +
this.age +
"\nDepartment: " +
this.department +
"\nBatch: " +
this.batch +
"\nRole: " +
this.role
);
}
}
let newEmployeeObject = new Employee1('person one',21,'computer science','2019','Trainee')
newEmployeeObject.getInfo()
Also check out - TypeScript Class TypeScript Polymorphism
Comments
Post a Comment