Home > DeveloperSection > Articles > Polymorphism

Polymorphism


.NET .NET 
Ratings:
0 Comment(s)
 3685  View(s)
Rate this:

Polymorphism in C#


When a message can be processed in different ways is called polymorphism.

Polymorphism is of two types: 

·         Overloading: In method overloading method performs the different task at the different input parameters with same method name and in same class.  

·         Overriding: Overriding a method is to change the behavior of the method for the derived class. Overriding is done using inheritance and virtual functions.

Example

To explain the concept of overloading I have created two classes Poly and abc(inherits poly).

//creating object of poly class

poly p = new poly();

    public class poly

    {

//these two functions, sum(), are overloaded.

        public int sum(int x, int y)

        {

            return (x + y);

        }

        public virtual int sum(int x, int y, int z)

        {

            return (x + y + z);

        }

    }

 

    public class abc : poly

    {

//overriding function sum(), of base class poly

        public override int sum(int x, int y, int z)

        {

            return (x + y + z + 10);

        }

    }

 

private void btnTwo_Click(object sender, EventArgs e)

        {

            int a, b,sum;

            a = int.Parse(textBox1.Text);

            b = int.Parse(textBox2.Text);

//calling sum(a,b) of poly

            sum = p.sum(a, b);

            MessageBox.Show("Sum of (Box 1 & 2): " + sum.ToString(), "Two parameters");

        }

 

        private void btnThree_Click(object sender, EventArgs e)

        {

            abc x1 = new abc();

            int a, b, c, sum,sum1,sum2;

            a = int.Parse(textBox1.Text);

            b = int.Parse(textBox2.Text);

            c = int.Parse(textBox3.Text);

            poly p = new poly();

//calling sum(a,b,c) of poly

            sum1=p.sum(a, b, c);

//calling override function sum()           

            p = new abc();

            sum2 = p.sum(a, b, c);

            MessageBox.Show("Sum of (Box 1, 2 & 3): " + sum1.ToString(), "Three Parameters");

            MessageBox.Show("Sum of (Box 1, 2 & 3): " + sum2.ToString(), "Three Parameters");

        }

 


Don't want to miss updates? Please click the below button!

Follow MindStick