In this blog we will discuss about Inheritance in TypeScript .
Introduction Inheritance :
Inheritance is the ability of one class to extend the functionality of another. The former is referred to as the Child Class or Sub Class, while the latter is referred to as the Parent Class or Super Class. As a result, Child Classes can inherit the properties (state) and functions (behaviour), and they can have additional class variables and functions, thus extending.
Syntax :
class ChildClassName extends ParentClassName{
// class body
}
Example :
class Person{
name:string
speak():void{
console.log(this.name+” can speak.”)
}
}
class Employee extends Person{
// variables
empnumber:number
// constructors
constructor(empnumber:number, name1:string){
super(); // calling Parent’s constructor
this.empnumber = empnumber
this.name = name1
}
// functions
displayInformation():void{
console.log(“Name : “+this.name+”, Emp number: “+this.empnumber)
}
}
var Employee1 = new Employee(5, “Abcd”)
var Employee2 = new Employee(6, “Xyz”)
// accessing variables
console.log(“Employee 1 name is : “+Employee1.name)
console.log(“Employee 2 Emp number is : “+Employee2.empnumber)
console.log(“\n—Employee 1—“)
// calling functions
Employee1.displayInformation()
// calling funciton of parent class
Employee1.speak()
console.log(“\n—Employee 2—“)
Employee2.displayInformation()
Employee2.speak()
Output:
Employee 1 name is : Abcd
Employee 2 Emp number is : 6
For any Help or Queries Contact us on info@crmonce.com or +918096556344