//
you're reading...
C# 3.0

Understanding Static & Dynamic Polymorphism with Examples.

Understanding Static & Dynamic Polymorphism with Examples.

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”);
    }
}

Cheers

Advertisements

About Vishal

Vishal Nayan is a seasoned professional with hand on Experience on Mircrosoft Technologies. He always look for challenging IT position that allows him to learn new Microsoft Technologies while utilizing experience of Project Development and Software Engineering Ethics. A MCP in WCF ,and looking forward for more.

Discussion

17 thoughts on “Understanding Static & Dynamic Polymorphism with Examples.

  1. Excellent.

    Posted by ipsita pani | 2012/01/17, 6:52 AM
  2. Nice Article

    Posted by Raj Kumar | 2012/01/18, 5:03 PM
  3. gr8 article

    Posted by shri | 2012/02/02, 1:02 PM
  4. I like it 🙂

    Posted by safi | 2012/03/27, 3:17 PM
  5. first time got this type of explanation…….thanks guru……..great.

    Posted by sanjoy banerjee | 2012/03/31, 5:38 PM
  6. I have understand this very clear thanks for this

    Posted by akash singh verma | 2012/04/11, 2:15 PM
  7. u done gr8 job explain it in very simple and understandable manner ……..keeep.

    Posted by Guddu | 2012/06/06, 12:01 PM
  8. superb article

    Posted by Arthu | 2012/10/31, 2:44 PM
  9. this is really usefull 🙂 😀

    Posted by anusha | 2012/11/28, 9:55 PM
  10. thank u…tooo much..:)

    Posted by sonu | 2013/02/09, 1:45 PM
  11. awesom but an entire programme with an execution trace would have been better to understand clearly bt thanks it helped a lot

    Posted by Tasu Sobti | 2013/03/29, 9:50 AM
  12. its realy goood….thank q…

    Posted by pavan antkul | 2013/04/01, 1:54 AM
  13. good one

    Posted by ramesh | 2013/07/01, 2:39 PM
  14. niceeeee (ijaz ali rana

    )

    Posted by RANA IJAZ ALI | 2014/02/13, 3:56 PM
  15. Is method overloading possible in case of a parent-child relationship? What I mean is, can I call a method of child class using a parent class object(parent is an abstract class)?

    Posted by jeff | 2014/04/24, 10:25 AM
  16. thank you

    Posted by ashu | 2015/10/24, 2:16 PM
  17. so, vry wanderful

    Posted by Dwimacha Basumatary | 2015/11/23, 1:45 PM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow Vishalnayan on WordPress.com

Blog Stats

  • 215,150 hits
%d bloggers like this: