Friday 4 January 2019

Polymorphism

Polymorphism (OOPS Principal): Poly + Morphism (Poly means Many and Morphism means change or faces/ behaviors)
Definition: Object changes behavior according to the condition. (one name having multiple forms)

There are two types:
1) Static or compile-time Polymorphism (eg: Method overloading, operator overloading)

2) Dynamic or run-time Polymorphism (eg: overriding using virtual and override keywords with inheritance)

Static Polymorphism: or Method Overloading
Example :  (at compile-time, the compiler decides which method to call)

class Program
{
  static void Main(string[] args)
  {
     Mathematics mathObj = new Mathematics();
     mathObj.Add(1,2);
     mathObj.Add(1,2,3);
     Console.ReadLine();
  }
}

class Mathematics
{
  public void Add(int value1, int value2)
  {
     Int result = value1 + value2;
     Console.Writeline(result);
  }

public void Add(int value1, int value2, int value3)
  {
     Int result = value1 + value2 + value3;
     Console.WriteLine(result);
  }
}

Dynamic Polymorphism: (Inheritance, Virtual and Overriding)

Example: (at run-time, the compiler will decide which method to call)

class Program
{
  static void Main(string[] args)
  {
// if we have one parent class with so many child classes, at runtime parent // class instance can call or point to any of the child class override mathod.
     
BaseClass obj = new ChildClass();
// parent class can now point to the child class
     obj.Test();
  }
}

class BaseClass
{
  public virtual void Test()
  {
     Console.Writeline("BaseClass Method");
  }
}

class ChildClass : BaseClass
{
 public override void Test()
  {
     Console.Writeline("ChildClass Method");
  }
}


Reference: csharpcorner & Questpond