RunTime Polymorphism in C#
In this article we are going to see, polymorphism in C#.So, What is a polymorphism in C# ? As the polymorphism word itself describes its defination which means multiple forms.Poly means "Multiple” or “Many” and Morphisum means “changing” or “converting”.So in C# , polymorphism works in two scenario which are Run time and Compile time. Now we will see Run time polymorphism which is Method Overriding. Method Overriding is a concept or an approach where we can create Methods with same name and same signature. (Signature means number of passed argument/parameters considering with their data type and sequence)Following is a simple program to understand it.
Code Snippet:-
/// <summary>
/// Parent Class
/// </summary>
public class ClassA
{
/// <summary>
/// Virtual Method
/// </summary>
/// <param name="_input"></param>
public virtual void WhatUgot(int _input)
{
Console.WriteLine("This is Original Virtual Method");
}
}
/// <summary>
/// Child Class
/// </summary>
public class ClassB:ClassA
{
/// <summary>
/// Overriden Mthod
/// </summary>
/// <param name="_input"></param>
public override void WhatUgot(int _input)
{
Console.WriteLine("This is Overriden Method");
}
}
public class RunTimePolymorph
{
public static void Main()
{
ClassB obj = new ClassB();
ClassA obj1 = new ClassB();
ClassA obj2 = new ClassA();
obj.WhatUgot(1);
obj1.WhatUgot(1);
obj2.WhatUgot(1);
Console.ReadLine();
}
}
In above example , We have created Method “WhatUGot” two times with same input parameters in two different classes which have parent child relationship. And it works at run time that’s why we called it as run time polymorphism. Point to remember is the Method Overriding is possible with two or more classes which are derived and inherited. It is not possible within same class.
Code Snippet:-
/// <summary>
/// Parent Class
/// </summary>
public class ClassA
{
/// <summary>
/// Virtual Method
/// </summary>
/// <param name="_input"></param>
public virtual void WhatUgot(int _input)
{
Console.WriteLine("This is Original Virtual Method");
}
}
/// <summary>
/// Child Class
/// </summary>
public class ClassB:ClassA
{
/// <summary>
/// Overriden Mthod
/// </summary>
/// <param name="_input"></param>
public override void WhatUgot(int _input)
{
Console.WriteLine("This is Overriden Method");
}
}
public class RunTimePolymorph
{
public static void Main()
{
ClassB obj = new ClassB();
ClassA obj1 = new ClassB();
ClassA obj2 = new ClassA();
obj.WhatUgot(1);
obj1.WhatUgot(1);
obj2.WhatUgot(1);
Console.ReadLine();
}
}
In above example , We have created Method “WhatUGot” two times with same input parameters in two different classes which have parent child relationship. And it works at run time that’s why we called it as run time polymorphism. Point to remember is the Method Overriding is possible with two or more classes which are derived and inherited. It is not possible within same class.
Comments
Post a Comment