❔ Polymorphism

can someone give a very simple example of polymorphism?
2 Replies
DaVinki
DaVinki2y ago
public class Program
{
public static void Main()
{
var animals = new Animal[]
{
new Bird(),
new Cow(),
new Human()
};

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

public abstract class Animal
{
public readonly Guid Uid;

public abstract void MakeSound();
}

public class Bird : Animal
{
public override void MakeSound()
{
Console.WriteLine("Tweet");
}
}

public class Cow : Animal
{
public override void MakeSound()
{
Console.WriteLine("Moo");
}
}

public class Human : Animal
{
public override void MakeSound()
{
Console.WriteLine("C# is cool");
}
}
public class Program
{
public static void Main()
{
var animals = new Animal[]
{
new Bird(),
new Cow(),
new Human()
};

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

public abstract class Animal
{
public readonly Guid Uid;

public abstract void MakeSound();
}

public class Bird : Animal
{
public override void MakeSound()
{
Console.WriteLine("Tweet");
}
}

public class Cow : Animal
{
public override void MakeSound()
{
Console.WriteLine("Moo");
}
}

public class Human : Animal
{
public override void MakeSound()
{
Console.WriteLine("C# is cool");
}
}
You have the animal class that all other classes are derived from And to show polymorphism in use, there's a little program that creates three animals of different types to have them all print their sound The array doesn't only hold birds, cows or humans. It holds animals which they all are You can think of it like all subclasses of Animal are "morphs" of Animal
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.