Understanding Static and Dynamic Polymorphism in .NET

No.of Views887
Bookmarked0 times
Downloads 
Votes0
By  Vishal Nayan   On  09 May 2011 08:05:15
Tag : .NET Frameworks , General
Poly means many. So how can we take this definition in .NET context. Well we can apply this to class’s ability to share the same methods (actions) but implement them differently.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

 What is polymorphism?

Poly means many. So how can we take this definition in .NET context. Well we can apply this to class’s ability to share the same methods (actions) but implement them differently.
Suppose we have a method in a class to add numbers,

public class calculation
{
    public int add(int x, int y)
    {
        return x + y;
    }
}

So to perform addition of three numbers, we need similar add method but with different parameter

public class calculation
{
    public int add(int x, int y)
    {
        return x + y;
    }
    public int add(int x, int y, int z)
    {
        return x + y + z;
    }
}

So we can that class is sharing the same methods (actions) but implement them differently.Now this is an example when we are sharing method name and implementing them differently, let’s take a scenario where implementation is in some derived class.For instance, say we create a class called Shape and this class has a method called .Area () which calculates area. Then we create two subclasses, using inheritance, of this Shape class.

One called Square, the other called Circle. Now obviously a square and circle are two entirely different shapes, yet both classes have the .Area() method. When the Square.Area() method is called it will calculate area of  a square. When the Circle.Area() method is called, it will calculate area of a circle. So both classes can use the same methods but implement them differently.

Now let’s dive little deeper and understand what we discussed above in more technical terms.

Types of Polymorphism

1)    Static or Compile time Polymorphism

Which method is to be called is decided at compile-time only. Method Overloading is an example of this. Method overloading is a concept where we use the same method name many times in the same class, but different parameters. Depending on the parameters we pass, it is decided at compile-time only. The same method name with the same parameters is an error and it is a case of duplication of methods which c# does not permit. In Static Polymorphism decision is taken at compile time.

public class StaticDemo
{
  public void display(int x)
 {
    Console.WriteLine("Area of a Square:"+x*x);
 }
  public void display(int x, int y)
 {
    Console.WriteLine("Area of a Square:"+x*y);
 }
 public static void main(String args[])
 {
    StaticDemo spd=new StaticDemo();
    Spd.display(5);
   Spd.display(10,3);
 }
}

2)    Dynamic or Runtime Polymorphism.
Run time Polymorphism also known as method overriding. In this Mechanism by which a call to an overridden function is resolved at a Run-Time (not at Compile-time) if a base Class contains a method that is overridden. Method overriding means having two or more methods with the same name, same signature but with different implementation. In this process, an overridden method is called through the reference variable of a superclass, the determination of the method to be called is based on the object being referred to by reference variable.

class BaseClass
{
  public void show ()
 {  
  Console.WriteLine("From base class show method");
    }
}
public class DynamicDemo : BaseClass
{
   public void show()
   {
         Console.WriteLine("From Derived Class show method");
   }
   public static void main(String args[])
   {
       DynamicDemo dpd=new DynamicDemo ();
      Dpd.show();
       
    }
}

Here memory allocation will be at the run time for that particular method.

What is Virtual Function:They implement the concept of polymorphism are the same as in C#, except that you use the override keyword with the virtual function implementation in the child class. The parent class uses the same virtual keyword. Every class that overrides the virtual method will use the override keyword.

Why to use them:

1)    It is not compulsory to mark the derived/child class function with Override KeyWord while base/parent class contains a virtual method
2)    Virtual methods allow subclasses to provide their own implementation of that method using the override keyword
3)    Virtual methods can't be declared as private.
4)    You are not required to declare a method as virtual. But, if you don't, and you derive from the class, and your derived class has a method by the same name and signature, you'll get a warning that you are hiding a parent's method
5)    A virtual property or method has an implementation in the base class, and can be overriden in the derived classes.
6)    We will get a warning if we won't use Virtual/New keyword.
7)    Instead of Virtual we can use New Keyword

class A
{
    public void M()
    {
        Console.WriteLine("A.M() being called");
    }

    public virtual void N()
    {
        Console.WriteLine("A.N() being called");
    }
}

class B : A
{
    public new void M()
    {
        Console.WriteLine("B.M() being called");
    }

    public override void N()
    {
        Console.WriteLine("B.N() being called");
    }
}

say,

A a = new B(); 

a.M(); 
a.N(); 

The results would be

A.M() being called
B.N() being called
 

Override Keyword: method overriding is modifying or replacing the implementation of the parent class with a new one. Parent classes with virtual or abstract members allow derived classes to override them.

class Shape
{
    public virtual void Draw()
    {
        Console.WriteLine("Shape.Draw");
    }
}

class Rectangle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Rectangle.Draw");
    }
}

That's all hope help and thank you for reading.

 
Sign Up to vote for this article
 
About Author
 
Vishal Nayan
Occupation-Software Engineer
Company-
Member Type-Junior
Location-India
Joined date-02 Apr 2011
Home Page-
Blog Page-http://vishalnayan.wordpress.com
Vishal is a seasoned professional with hand on experience on Microsoft technologies. He always look for challenging assignment that allows him to learn newer technologies while utilizing his experience of project development and software engineering ethics. In spare time vishal can be found reading business and political personalities, acts as critics at columnist , writing poetries, bird watching , singing ,cooking. He have strong interests in Indian business and political arena and want to be an active one someday. He is also a part-time trainer on framework , WCF and Silverlight. reach him at vishalnayan@gmail.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top