Tuesday, September 4, 2018

Typescript - Understanding Polymorphism with examples

In this Blog Post, We are going to learn the Beginner guide to Polymorphism concept in typescript.
Typescript Polymorphism  Tutorials with examples

Polymorphism Tutorial Introduction

It is one of the concepts of Object Oriented Programming. Other concepts are ClassesInterfaces , Encapsulation and Abstract classes.

Polymorphism means many forms of a function or method in a class
Typescript supports polymorphism concept in many ways.
  • function overloading
  • function overriding
  • Interface

Method overriding

Method overriding is allowed Child class to provide an implementation of a function or method that is already provided by Superclass or Parent class.
The subclass will have access to all public methods and properties of a Superclass

Rules

A function declared in child class must have the same name as the parent class
Parameters of a function in parent and child classes are same
child classes extend by parent class or follow the inheritance 

Example

In this, We have declared Parent and Child classes. The parent class is extending from Child class. These two classes have the same method name processName()
Here processName() is overriding in the child class and providing an implementation.
class Parent {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    processName() {
        console.log('processName method in parent class',name)
    }
}
class Child extends Parent {
    constructor(name: string) {
        super(name);
    }
      processName() {
        console.log('processName method in Child class',name)
    }
}
let myObject = new Child("Kiran");
myObject.processName()
let myObject1= new Parent("john");
myObject1.processName()
Output is
processName method in Child class 
processName method in parent class 

Method or Function overloading

Function overloading means one method with multiple signatures. Every programming language provides the same. But typescript supports in a different way. For example, In Typescript, If we write multiple methods with the different argument as per another programming language like below
class MyClass {
    constructor() {

    }
    mymethod() {
        console.log('method with No argument');
    }
    mymethod(name: string) { 
        console.log('method with string argument');
    }
}
let myclass = new MyClass();
console.log(myclass.mymethod());
This will not Compile and gives error Duplicate function implementation The reason, Typecode converted to javascript and javascript has no overloading syntax support.
Then How typescript supports functional overload? 
yes, It supports function overload in a different way using Any Data type or Optional Parameter Syntax. You can check my other blog post on Function overload in typescript

Polymorphism Interfaces  or Duck Typing

For Example, We have Interface - DatabaseConnection which has an only abstract method - connect() use to connect database and return >0 if successful, else return zero or -1 for failed cases.
interface DatabaseConnection{
    connect(): number;
}
We will provide an implementation for DatabaseConnection interface. Let us say, provide an implementation for MySQL database. MySQLConnection has connect() method implementation for MySQL Database
export class MySQLConnection implements DatabaseConnection{
    public connect(): number{
        console.log("Open HTTP Connection");
        console.log("Connection Established");
        return 1;
    }
}
Also, provide the Database connection mechanism for MongoDB. MongoDBConnection has connect() method implementation for MongoDB Database
export class MongoDBConnection implements DatabaseConnection{
    public connect(): number{
        console.log("Open HTTP Connection");
        console.log("Connection Established");
        return 1;
    }
}
Next step is to write a Client code which connects to Database. DatabaseTest class is created and provided constructor by injecting DatabaseConnection.
This is an example for Constructor Injection using interfaces. So you are passing interface here, Not implementation. The client need not required whether the connection to MySQL or MongoDB or something else? The advantages of the passing interface is flexibility and loosely coupling between components and easy in doing unit testing of components. Implementation of Db is decided at Runtime here. This is called polymorphism interface This adds more flexibility, enables clients to configure
export class DatabaseTest {
    constructor(private dbConnection: DatabaseConnection) {
        dbConnection.connect()
    }
}
if we inject implementation class MongoDBConnection in a constructor, This is tightly coupled, and not able to extend for future implementations.

Related article


EmoticonEmoticon