Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and when use polymorphism?

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

like image 841
lombardo2 Avatar asked Oct 06 '12 02:10

lombardo2


People also ask

What is polymorphism and why or how it is used?

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.

Why polymorphism is used in oops?

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.


1 Answers

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());
}
like image 75
MikeB Avatar answered Sep 23 '22 12:09

MikeB