Polymorphism Example in C# - Biz Tech

Polymorphism Example in C#

Listen
using System;

class Program
{
    static void Main(string[] args)
    {
        Animal[] animals = new Animal[2];
        animals[0] = new Dog("Rufus");
        animals[1] = new Cat("Fluffy");

        foreach (Animal animal in animals)
        {
            animal.MakeSound();
        }
    }
}

class Animal
{
    protected string name;

    public Animal(string name)
    {
        this.name = name;
    }

    public virtual void MakeSound()
    {
        Console.WriteLine(name + " makes a sound.");
    }
}

class Dog : Animal
{
    public Dog(string name) : base(name)
    {
    }

    public override void MakeSound()
    {
        Console.WriteLine(name + " barks.");
    }
}

class Cat : Animal
{
    public Cat(string name) : base(name)
    {
    }

    public override void MakeSound()
    {
        Console.WriteLine(name + " meows.");
    }
}
 

In this example, we have a base class Animal and two derived classes Dog and Cat. The base class Animal has a MakeSound() method that outputs a message indicating that the animal makes a sound. The Dog and Cat classes override the MakeSound() method to output a message indicating that the animal barks or meows, respectively.

In the Main() method, we create an array of Animal objects, containing one Dog object and one Cat object. We then loop through the array and call the MakeSound() method on each object. Because Dog and Cat inherit from Animal, we can treat them as Animal objects and call the MakeSound() method on them. This demonstrates polymorphism, where objects of different types can be treated as objects of the same base class, and their behavior can be determined by their specific type.

When we run the program, it outputs the following:

Rufus barks.

Fluffy meows.

This demonstrates that the MakeSound() method of each object is called, and the output reflects the behavior specific to the Dog and Cat classes.