Monday, May 6, 2013

Polymorphism in asp.net

In this post i will show how Polymorphism (OOPS) is implemented in asp.net with the help of an example:

Polymorphism : It states that the same method names exhibit different behaviors according to the condition applied.

Types of Polymorphism:
1. Compile Time polymorphism (Method Overloading)
- In this we have same method name but the no of arguments can be different.

2. Run time polymorphism (Method Overriding)
- In this we skip calling the base method and instead call the derived method which is of the same name as of the base class.

Example Compile Time polymorphism :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class polymorphism : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Over loading
        int val = add(10);
        Response.Write("<Script language='Javascript'>alert('Result: " + val + "');</Script>");
        int val1 = add(10, 20);
        Response.Write("<Script language='Javascript'>alert('Result: " + val1 + "');</Script>");
        int val2 = add(10, 20, 30);
        Response.Write("<Script language='Javascript'>alert('Result: " + val2 + "');</Script>");
    }

    public int add(int x)
    {
        return x;
    }

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

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

Example Run Time polymorphism :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class polymorphism : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
         //Overridding
        displayBaseMessage d1 = new displayMessage();
        string s = d1.messg();
        Response.Write("<Script language='Javascript'>alert('Result: " + s + "');</Script>");
    }
}

public class displayBaseMessage
{
    public virtual string messg()
    {
        string s = "From Base class";
        return s;
    }
}
public class displayMessage : displayBaseMessage
{
    public override string messg()
    {
        string s = "From Derived class";
        return s;
    }
}


No comments:

Post a Comment