Polymorphism - DotNet and DataBase

Tuesday, 24 July 2018

Polymorphism



Polymorphism is a Greek word. Poly means "many" and morphism means for"forms". So, the exact meaning is "many forms".
So, here in C#.net, we can access different classes using one object. So, it is exactly suitable word here.

Polymorphism is two types.
1)Run time polymorphism
2)Compile time polymorphism

Runtime polymorphism:
Run time polymorphism is also called as method overriding or dynamic polymorphism or late binding. Run time polymorphism or method overriding means we can create same method names with same count of paramters/same type of parameters.
In this run time polymorphism or method overriding we can override a method in base class by creating similar function in derived class this can be achieved by using inheritance process by using “virtual & override” keywords.
In base class we should declare the methods with virtual keyword then only we can override those methods in derived class using override keyword
Example:
using System;

//Base Class
public class Baseclass
{
    public virtual void Basemthod()
    {
        Console.WriteLine("I'm the Base Class method");
    }
}
// Derived Class
public class DerivedClass : Baseclass
{
    public override void Basemthod()
    {
        Console.WriteLine("I'm the Derived Class method");
    }
}
public class Program
{
 public static void Main()
 {
     // calling the overriden method
        DerivedClass objDc = new DerivedClass();
        objDc.Basemthod();
        // calling the base class method
        Baseclass objectBaseclass = new DerivedClass();
        objectBaseclass.Basemthod();
 }
}


Compile time polymorphism:
Compile time polymorphism means more than one method exists with same under one class but different paramters(either type or count) is different. Because of this we can perform different tasks with same method name. This compile time polymorphism also called as early binding or method overloading.

Method Overloading or compile time polymorphism means same method names with different signatures
Example:
using System;

    public class Mathematics
{
  public int AddNumbers(int a, int b)
   {
     int c= a + b;
     return c;
   }
  public int AddNumbers(int a, int b, int c)
   {
     int d = a + b+c; 
     return d;
   }
}


public class Program
{
 public static void Main()
 {
     // calling the overriden method
        Mathematics math = new Mathematics();
        Console.WriteLine(math.AddNumbers(2,3));
  Console.WriteLine(math.AddNumbers(2,3,4));
  
 }
}

In the above example, I have created two methods with the same name (AddNumbers) but the count of Parameters are different.




Practice

No comments:

Post a Comment

x

Get Updates On

Discussion updates

Straight Into Your INBOX!

Enter your email address to subscribe to this website and receive notifications of new posts by email.