- Back to Home »
- C#.NET »
- C#.NET Polymorphism
Posted by :
Sudhir Chekuri
Saturday, 9 January 2016
Polymorphism means "Many forms".
In other words it can be defined as entities behave in different forms based on the given input i.e., whenever there is a change in the input the output on behavior also changes.
Polymorphism can be of two types.
1. Static Polymorphism or Method Overloading
2. Dynamic Polymorphism or Method Overriding
Example program for Method Overloading
Program
Output
Maths Add
Maths : 3
Maths : 7
Example program for Method Overriding
Program
Output
-2
Example program for Method Overriding and calling Parent method
Output
Maths A Add
In other words it can be defined as entities behave in different forms based on the given input i.e., whenever there is a change in the input the output on behavior also changes.
Polymorphism can be of two types.
1. Static Polymorphism or Method Overloading
2. Dynamic Polymorphism or Method Overriding
C#.NET Method Overloading
It is also known as "Compile time polymorphism”. It can have same method name and different parameters. It is also known as "Method Overloading".Example program for Method Overloading
Program
using System;
namespace Overloading
{
class Program
{
static void Main(string[] args)
{
Maths a = new Maths();
a.Add();//Maths
Add
a.Add(3);//Maths
: 3
a.Add(2, 5);//Maths
: 7
Console.ReadKey();
}
}
class Maths
{
public void Add()
{
Console.WriteLine("Maths Add");
}
public void Add(int a)
{
Console.WriteLine("Maths : " + a);
}
public void Add(int a, int b)
{
Console.WriteLine("Maths : " + (a + b));
}
}
}
Output
Maths Add
Maths : 3
Maths : 7
C#.NET Method Overriding
It is also known as "Run time polymorphism”. It can have same method name and same signature. It is also known as "Method Overriding”. Method Overriding can be used only when we have inheritance.Example program for Method Overriding
Program
using System;
namespace MethodOverriding
{
class Program
{
static void Main(string[] args)
{
y o = new y();
o.add(1, 3);
Console.ReadKey();
}
}
class x
{
public void add(int a, int b)
{
Console.WriteLine(a + b);
}
}
class y : x
{
public void add(int a, int b)
{
Console.WriteLine(a - b);
}
}
}
Output
-2
Example program for Method Overriding and calling Parent method
using System;
namespace Overriding
{
class Program
{
static void Main(string[] args)
{
MathsB b = new MathsB();
b.Add();
Console.ReadKey();
}
}
class MathsA
{
public void Add()
{
Console.WriteLine("Maths A Add");
}
}
class MathsB : MathsA
{
public void Add()
{//Calling parent method from child
method
base.Add();
Console.WriteLine("Maths B Add");
}
}
}
Output
Maths A Add