Contracts in OOPS:
A contract defines a set of rules which are mandatory for any component to implement any specific functionality.
In OOPS, contracts are defined by using interface
An interface specifies rules for any component.
Interface comprises of members which are by default public in access. Hence access specifiers are not required for an member in interface.
Syntax:
interface Name {
property:type;
}
Interface can be implemented by using a class with "implements" keyword.
Syntax:
class ClassName implements interfaceName
A member can implement the contract by using it as a type
Syntax
public property: interfaceName;
Every members defined in contract is not nullable, i.e reference for the member must be defined in implementation.
You can designate the non nullable members into nullable i.e optional by using a null reference character ( " ? " )
Example
interface Iproduct {Name:string;Price: number;Qty? :number;}let products: Iproduct= {Name: "TV", Price: 345}console.log("Name=" + products.Name);console.log("Price=" + products.Price);console.log("Quantity=" + products.Qty);
Output:
Name=TV Price=345 Quantity=undefined PS C:\Examples>Example 2:
interface Product {Name:string;Price: number;Qty? :number;}let products: Product[] =[{ Name: "TV", Price: 345 },{ Name: "Mobile" , Price : 43 ,Qty:2 }];for(var item in products){console.log(products[item]);}Output:{ Name: 'TV', Price: 345 } { Name: 'Mobile', Price: 43, Qty: 2 }
The interface members are by default virtual. Hence they can be overidden any number of times.
You can restrict the override after initialization by using "read only"
Example
const is associated with variablesreadonly is associated with properties.Interface Methods:
The method specifies action for any componentsThe method are represented with " () "The method are implemented by the keyword "function"Syntaxinterface Name {(params) : returnType}Exampleinterface IMethod {():string}let myMethod:IMethod;myMethod=function():string {return "Welcome";}console.log(myMethod());Output:WelcomeCombination of properties and Methodsinterface IMethod {Id:number;Name:string;price:number;isAvailable:boolean;Qty:number;Total(Qty:number,price:number):number;}let myMethod:IMethod= {Id:1,Name:"TV",price: 4444,Qty:2,isAvailable:true,Total(Qty: number, price : number) {return Qty * price}}console.log(myMethod.Qty);console.log("Total= " + myMethod.Total(myMethod.Qty,myMethod.price))Output2 Total= 8888Extending InterfaceAn interface defined with specified rules can be extended with more functionality byusing "extends" keywordsinterface Iversion1{notepad:string;}interface Iversion2 extends Iversion1 {mspaint:string;}let appversion: Iversion2= {mspaint:"Text-Paint",notepad:"Text-Editor",}console.log(appversion.mspaint);console.log(appversion.notepad);OutputText-Paint Text-EditorExampleinterface IBackEffect{bgcolor:string;bgimage:string;}interface ITextEffects{align:stringforecolor:string}interface IEffects extends IBackEffect,ITextEffects {border:number;}let effects: IEffects= {bgcolor:"red",align:"center",border:2,forecolor:"white",bgimage:"shipimage"}console.log(effects.bgcolor);console.log(effects.align);console.log(effects.border);console.log(effects.forecolor);Output
red center 2 white
interface IEmployee {empId: number;name: string;getSalary:(empCode: number) => number;}class Employee implements IEmployee {empId: number;name: string;constructor(Id: number, name: string) {this.empId = Id;this.name = name;}getSalary(empCode:number):number {return 20000;}}let emp = new Employee(1, "Uday");
Example of Interface with Arrow Function
interface IEmployee {empId: number;empName: string;getSalary: (number) => number;getManagerName(number): string;}
Interface as Type
Interface in TypeScript can be used to define a type and also to implement it in the class.
Interface is used as type of variable
interface KeyPair {key: number;value: string;}let kv1: KeyPair = { key:1, value:"Uday" }; // OKlet kv2: KeyPair = { key:1, val:"Kumar" }; // Compiler Error: 'val' doesn't exist in type 'KeyPair'let kv3: KeyPair = { key:1, value:100 }; // Compiler Error:
Example
interface Idraw{ area(); }class circle implements Idraw{constructor(private radius:number) {}area() {let result=3.14*this.radius*this.radius;console.log("area of circle:"+result);}}class rect implements Idraw{constructor(private l:number,private b:number) {}area() {let result=this.l*this.b;console.log("area of rect:"+result);}}let circleobj=new circle(6);let rectobj=new rect(5,7);circleobj.area();rectobj.area();//polymorphismconsole.log("result with polymorphism:")let draw:Idraw;draw=new circle(6);draw.area();draw=new rect(5,7);draw.area();Output
Note:
----- *interface doesn't allow object creation, but variable can be declared *interface can reference to an object of a class,which implements an interface *interface can implement polymorphism d=new circle(6); d.area(); d=new rect(6,7); d.area() ==> d.area() is providing more than one form[behavior] is called polymorphism, this consumes less memory resources compare to normal approach
No comments:
Post a Comment
Thank you for visiting my blog