Another Polymorphism Example

suggest change

Polymorphism is one of the pillars of OOP. Poly derives from a Greek term that means “multiple forms.”

The example below exhibits polymorphism. The class Vehicle takes multiple forms as a base class.

The derived classes Ducati and Lamborghini inherit from Vehicle and override the base class’s Display() method to display their 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()
    {
        NumberOfWheels = 2;
    }

    public override void Display()
    {
        Console.WriteLine($"The number of wheels for the {nameof(Ducati)} is {NumberOfWheels}");
    }
}

public class Lamborghini : Vehicle
{
    public Lamborghini()
    {
        NumberOfWheels = 4;
    }

    public override void Display()
    {
        Console.WriteLine($"The number of wheels for the {nameof(Lamborghini)} is {NumberOfWheels}");
    }
}

The snippet below exhibits polymorphism. A Vehicle variable is created at line 1. It calls the base-class Display() method at line 2 and displays the output shown below.

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, vehicle is assigned a Ducati and calls that type’s Display() method. This is the polymorphic behavior: even though the variable’s compile-time type is Vehicle, the call uses Ducati’s override because the object is a 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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents