Polymorphism is one of the pillar of OOP. Poly derives from a Greek term which means 'multiple forms'.
Below is an example which exhibits Polymorphism. The class Vehicle
takes multiple forms as a base class.
The Derived classes Ducati
and Lamborghini
inherits from Vehicle
and overrides the base class's Display()
method, to display its own NumberOfWheels
.
public class Vehicle
{
protected int NumberOfWheels { get; set; } = 0;
public Vehicle()
{
}
public virtual void Display()
{
Console.WriteLine($"The number of wheels for the {nameof(Vehicle)} is {NumberOfWheels}");
}
}
public class Ducati : Vehicle
{
public Ducati()
{
NoOfWheels = 2;
}
public override void Display()
{
Console.WriteLine($"The number of wheels for the {nameof(Ducati)} is {NumberOfWheels}");
}
}
public class Lamborghini : Vehicle
{
public Lamborghini()
{
NoOfWheels = 4;
}
public override void Display()
{
Console.WriteLine($"The number of wheels for the {nameof(Lamborghini)} is {NumberOfWheels}");
}
}
Below is the code snippet where Polymorphism is exhibited. The object is created for the base type Vehicle
using a variable vehicle
at Line 1. It calls the base class method Display()
at Line 2 and display the output as shown.
static void Main(string[] args)
{
Vehicle vehicle = new Vehicle(); //Line 1
vehicle.Display(); //Line 2
vehicle = new Ducati(); //Line 3
vehicle.Display(); //Line 4
vehicle = new Lamborghini(); //Line 5
vehicle.Display(); //Line 6
}
At Line 3, the vehicle
object is pointed to the derived class Ducati
and calls its Display()
method, which displays the output as shown. Here comes the polymorphic behavior, even though the object vehicle
is of type Vehicle
, it calls the derived class method Display()
as the type Ducati
overrides the base class Display()
method, since the vehicle
object is pointed towards Ducati
.
The same explanation is applicable when it invokes the Lamborghini
type's Display()
method.
The Output is shown below
The number of wheels for the Vehicle is 0 // Line 2
The number of wheels for the Ducati is 2 // Line 4
The number of wheels for the Lamborghini is 4 // Line 6