You are on page 1of 6

inheritance:

------------
*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(){..}

*typescript is providing "extends" keyword to work with inheritance


*syntax:
class <dervclass> extends <baseclass>
{
...
constructor(--)
{
super(-);
..
}
<methodname>(--)
{
super.methodname(-);
..
}
}

*derv class can reference base class using "super" keyword

*typescript allows only one base class for derv class

class1 ---> single level inheritance


|
class2

class1 --> multi level inheritance


|
class2
|
class3

class1 class2 --> multiple inheritance [not allowed]


|
class3

method overriding:
------------------
*derv class is providing same method name and signature of base class
is called "method overriding"

signature--> numb of paras

*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

let cobj=new customer(---)---> person object


name-
age-
constructor(--)
display(){}
|
customer object
custid-
constructor(---)
{ super(name,age);
display(){..}

*constructor para attached with access specifier will autogenerate


class field with the para name and para will be assigned to
class field automatically

class person class person{


{ private name:string;
constructor(private name:string, -----> private age:number;
private age:number) constructor(name:string,age:number)
{} { this.name=name;
.. this.age=age;
} }
...
}

You might also like