Definition 1: The ability to take more than one form.
Definition 2: Same operation may work in different way on other classes.
Basically polimorphism are two types:
1. Compile time polymorphism: for example method overloading
2. Run time polymorphism: for example method overriding
Compile time polymorphism: Method Overloading
In this, calss is this having same method name and different arguments. This is check at compile time only. So we can call it as compile time polimorphism
class Compile
{
public string method(string first)
{
return first;
}
public string method()
{
return "no argument";}
}
}
Run Time Polymorphism:Overriding
Method overriding occurs When the child class is having same method name with arguments count and type by one of its superclass
class BaseClass
{
public virtual void OverrideExample()
{
Console.WriteLine("base method");
}
}
class DerivedClass : BaseClass
{
public override void OverrideExample()
{
Console.WriteLine("derived method");
}
}
class Test
{
static void Main(string[] args)
{
BaseClass a;
DerivedClass b;
a = new BaseClass();
b = new DerivedClass();
a.OverrideExample(); // output --> "base method"
b.OverrideExample(); // output --> "derived method"
a = new DerivedClass();
a.OverrideExample(); // output --> "derived method"
Console.ReadLine();
}
}
No comments:
Post a Comment