Professional Documents
Culture Documents
------------
*creating a new class based on existing class is called "inheritance"
*this provides reusability
class1 [base|super class]
|
m1(){..}
m2(){..}
|
class2 [derv|sub class]
m1() and m2()-->getting from class1
m3(){..}
method overriding:
------------------
*derv class is providing same method name and signature of base class
is called "method overriding"
*method overriding will hide base class functionality with derv class
object
class1
m1()
|
class2 ------> obj --> obj.m1()
m1()--overriding
base class[class1] method m1
*requirement:
person class
name and age fields
display()
| ------------------->inheritance
customer class employee class
custid empid
display() display() ---> method overriding
eg:
---
*create a new file
inheritancedemo.ts
|
//base class
class person
{
constructor(private name:string,private age:number)
{}
display()
{
console.log("name:"+this.name+" age:"+this.age);
}
}
//derv class
class customer extends person
{
private custid:string;
constructor(name:string,age:number,custid:string)
{
super(name,age);//calling base class constructor to initialize base object
this.custid=custid;
}
display()
{
console.log("custid:"+this.custid);
super.display();//it will display name and age
}
}
//create derv class object
let cobj=new customer("charan",14,"c001");
cobj.display();
*goto terminal
>tsc inheritancedemo.ts
>node inheritancedemo
custid:c001
name:charan age:14
note:
-----
*creating an object to derv class will create an object to base class
internally