Thursday, September 21, 2023

Polymorphism in Typescript Part -9

 It is the characteristics of OOPS.

 The term poly means many and morphos means forms

It defines a feature that allows the component to have multiple behaviour.

Technically it is possible by allocating different types of memory for single component

Polymorphism is configuring single base class object that can use the memory of multiple derived class.


Example

class Employee
{
    public fname:string="Pawan";
    public lname:string="Kalyan";
    public print():void {
        console.log(this.fname+ "" + this.lname);
    }
}
class PartTimeEmployee extends Employee
{
    public print():void {
        this.fname="Raj";
        this.lname="Kumar";
        console.log(this.fname+ "" + this.lname);
    }
}
class FullTimeEmployee extends Employee
{
    public print():void {
        this.fname="Kiran";
        this.lname="Kumar";
        console.log(this.fname+ "" + this.lname);
    }
}
let employee=new Array();
employee[0]=new Employee();
employee[1]= new PartTimeEmployee();
employee[2]=new FullTimeEmployee();
for(var i=0;i<employee.length;i++) {
    employee[i].print();
}

Function Overloads


In TypeScript, you can create multiple functions with the same name but different parameter types and return types. But, the number of parameters should be exactly the same, only the data type can differ.

function add(a: number, b: number): number;

function add(a: string, b: string): string;


function add(a: any, b: any): any {
    let n= a + b;
    console.log(n);
}
add(5, 20);
add('Hello', 'CodingNinjas');

Output
25


Function overloading with different number of parameters and types with same name is not supported.

function display(a:string, b:string):void //Compiler Error: Duplicate function implementation
{
    console.log(a + b);
}

function display(a:number): void //Compiler Error: Duplicate function implementation
{
    console.log(a);
}

Method overriding:
------------------
derv class redeclaring base class method with the same signature is called "method overriding"

OR

derv class method name and signature is same as base class method is called
"method overriding"


Example

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(custid:string,name:string,age:number)
    {
        super(name,age);//initializing base object
        this.custid=custid;
    }
    display()
    {
        console.log("custid:"+this.custid);
        super.display();//calling base method to display name and age
    }
}
let cobj=new customer("c001","raju",20);
cobj.display();


Output
PS C:\Examples> tsc.cmd methodoveriding.ts PS C:\Examples> node methodoveriding custid:c001 name:raju age:20


Note:
note:
-----

*Attaching access specifier to constructor paras will generate class fields
with the same name as paras and assigning paras to class fields will be
done automatically, this will reduce lot of coding to developer.

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



Inheritance In Typescript Part 8

 Inheritance:

It is one of the key feature of OOPS.

It enables code extensibility and allows loosely coupled architecture.

It is the process of creating a new class that extends existing class.

The newly created class is known as derived class and existing class is known as super class.

typescript is providing "extends" to work with inheritance

Syntax:


class Super

{

    //Super Class Members

}

class Derived extends Super {

//Derived class Members

}

The code can be reused by using Inheritance which is known as Has a Relation

The members of super class are accessible in derived class by using the keyword "this"

Syntax with constructor

syntax:
   class <derv|sub classname>  extends <base|super classname>
   {
     constructor(--)
     {
        super(--); //calling base constructor to initialize base class fields
        initialize derv class fields
     }
     <methodname>(--)
     {
       super.<methodname>(--);
        ...
     }
      ...
   }
class Base
{
    public x:number=10;
}
class Derived extends Base{
    public y:number=20;
    public print():void {
        console.log("x=" + this.x + "\n" + "y=" + this.y);
    }
}
let objderived=new Derived();
objderived.print();

Output:

x=10 y=20


Will typescript supports multiple inheritance for a class
No

Why multiple inheritance is not supported for classes.
Inheritance depends on constructor, when you create a derived class object, first
base class constructor is called than followed by derived. If they are multiple base
classes then there will be conflicts between the constructors. Hence multiple inheritance
is not supported.

MultiLevel Inheritance

It is the process, where in derived class can be extended by new class , so that
it can be access both derived and super class members.

Example

class ProductId {
    public Id:number;
}
class Details extends ProductId
{
    public Name:string;
    public Price:number;
}
class ProductInfo extends Details
{
    public print():void {
        console.log("Id="+ this.Id);
        console.log("Name="+ this.Name);
        console.log("Price="+ this.Price);
    }
}
let objproductInfo=new ProductInfo();
objproductInfo.Id=1;
objproductInfo.Name="Samsung";
objproductInfo.Price=4353;
objproductInfo.print();


Output:

Id=1
Name=Samsung
Price=4353



Example 2

class Department {
    name: string;
   
    constructor(name: string) {
        this.name = name;
    }
}

class  Employee extends Department {
    empCode: number;
   
    constructor(empcode: number, name:string) {
        super(name);
        this.empCode = empcode;
    }
   
    displayName():void {
        console.log("Department Name = " + this.name +  ", Employee Code = " + this.empCode);
    }
}

let emp = new Employee(100, "IT");
emp.displayName();


Output:

Department Name = IT, Employee Code = 100

Note: In the above example
The constructor of the Employee class initializes its own members as well as the parent class's properties using a special keyword 'super'. The super keyword is used to call the parent constructor and passes the property values.


Class implements Interface


interface IPerson {
    name: string;
    display():void;
}

interface IEmployee {
    empId: number;
}

class Employee implements IPerson, IEmployee {
    empId: number;
    name: string;
   
    constructor(empId: number, name:string) {
        this.empId = empId;
        this.name = name;
    }
   
    display(): void {
        console.log("Name = " + this.name +  ", Employee Id = " + this.empId);
    }
}

let per:IPerson = new Employee(100, "Uday");
per.display(); // Name = Bill, Employee Code = 100

let emp:IEmployee = new Employee(100, "Uday");
emp.display(); //Compiler Error: Property 'display' does not exist on type 'IEmployee'



Contracts in OOPS(Typescript Part 7 )

 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




Difference between read only / const is
const is associated with variables
readonly is associated with properties.

Interface Methods:

The method specifies action for any components
The method are represented with " () "
The method are implemented by the keyword "function"

Syntax

interface Name {
(params) : returnType
}


Example

interface IMethod {
    ():string
}
let myMethod:IMethod;
myMethod=function():string {
    return "Welcome";
}
console.log(myMethod());

Output:

Welcome

Combination of properties and Methods

interface 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))

Output

2 Total= 8888

Extending Interface

An interface defined with specified rules can be extended with more functionality by
using "extends" keywords

interface 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);

Output

Text-Paint Text-Editor


Example
interface IBackEffect
{
    bgcolor:string;
    bgimage:string;
}
interface ITextEffects
{
    align:string
    forecolor: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" }; // OK

let 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();
//polymorphism
console.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







Interview Question Difference between let vs var & const in Type Script (Part 7)

 Advantages of using let over var

We cannot read or write before they are declared , if the variable is declared as let .Whereas it won't give an error when using variables before declaring them using var.

console.log(num1);
let num1:number = 10 ;

console.log(num2);
var num2:number = 10 ;

Output



variables declared with let cannot be re-declared

The TypeScript compiler will give an error when variables with the same name (case sensitive) are declared multiple times in the same block using let.

Whereas it wont give any error when declaring variable with var.

var num:number = 02; // OK
var Num:number = 22;// OK
var NUM:number = 34;// OK
var NuM:number = 444;// OK

let num:number = 52;// Compiler Error: Cannot redeclared block-scoped variable 'num'
let Num:number = 66;// Compiler Error: Cannot redeclared block-scoped variable 'Num'
let NUM:number = 77;// Compiler Error: Cannot redeclared block-scoped variable 'NUM'
let NuM:number = 88;// Compiler Error: Cannot redeclared block-scoped variable 'NuM'
Note:
Variables with the same name and case can be declared in different blocks using let.

const
Variables can be declared using const as well. If declared const it values cannot be changed

const num:number = 100;
num = 200; //Compiler Error: Cannot assign to 'num' because it is a constant or read-only property

Const variables must be declared and initialized in a single statement. Separate declaration and initialization is not supported.

const num:number; //Compiler Error: const declaration must be initialized
num = 100; 

Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...