Polymorphism is one of the powerful OOPs features in .Net. The word polymorphism means 'many forms', a type or a class can have different forms.
When a class is derived from a base class, it inherits the base class's members and methods.
There are two options here:
a. The derived class can replace the base class method completely with the new implementation. This is achieved by using 'new' keyword in the derived class method. The derived class method can be called using derived class's instance. Whereas the base class method can be called by casting the derived class instance to the base class.
Let’s see this by an example to understand clearly.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Vehicle
{
class Program
{
class car
{
public car() { }
public virtual void body()
{
Console.WriteLine("Generic car model");
}
}
class sedan : car
{
public sedan() { }
public new void body()
{
Console.WriteLine("4 door car model");
}
}
class coupe : car
{
public coupe() { }
public new void body()
{
Console.Write("2 door car model");
}
}
static void Main(string[] args)
{
sedan _sedan = new sedan();
_sedan.body(); //prints "4 door car model"
//case derived class instance to base class to call the base class's method.
((car)_sedan).body(); //prints "Generic car model"
Console.Read();
}
}
}
b. The derived class can inherit the base class's method implementation completely. The derived class method can also add its own implementation in addition. This can be achieved by overriding the virtual base class method. That means that the base class method should be defined with the 'virtual' keyword and the derived class method should be defined using 'override' keyword.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Vehicle
{
class Program
{
class car
{
public car() { }
public virtual void body()
{
Console.WriteLine("Generic car model");
}
}
class sedan : car
{
public sedan() { }
public override void body()
{
base.body();
Console.WriteLine("4 door car model");
}
}
class coupe : car
{
public coupe() { }
public override void body()
{
Console.Write("2 door car model");
}
}
static void Main(string[] args)
{
sedan _sedan = new sedan();
_sedan.body(); //prints "Generic car model" followed by "4 door car model"
Console.Read();
}
}
}
Thanks for sharing this valuable article.
Angularjs Training in Chennai