I'm new to OOP and polymorphism has given me a hard time:
class Animal
{
public virtual void eat()
{
Console.Write("Animal eating");
}
}
class Dog : Animal
{
public override void eat()
{
Console.Write("Dog eating");
}
}
class Program
{
public void Main()
{
Animal dog = new Dog();
Animal generic = new Animal();
dog.eat();
generic.eat();
}
}
So that prints
Dog eating
Animal eating
But why not to just use the Dog type instead of animal, like Dog dog = new Dog()? I assume this comes handy when you know the object is a animal, but don't know what kind of animal it is. Please explain this to me.
Thanks
Polymorphism is one of the core concepts of object-oriented programming (OOP) and describes situations in which something occurs in several different forms. In computer science, it describes the concept that you can access objects of different types through the same interface.
Polymorphism is one of the most important concept of object oriented programming language. The most common use of polymorphism in object-oriented programming occurs when a parent class reference is used to refer to a child class object. Here we will see how to represent any function in many types and many forms.
You can refer to a subclass by its super class.
Animal dog = new Dog();
Animal cat = new Cat();
Animal frog = new Frog();
List<Animal> animals = new List<Animal>();
animals.add(dog);
animals.add(cat);
animals.add(frog);
foreach(Animal animal in animals)
{
Console.WriteLine(animal.eat());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With