AL-zami
AL-zami

Reputation: 9066

Explanation of a certain polymorphic behavior in C#

I've found that it is possible to create an instance of a child class and assign it to a variable of type parent class. I cannot wrap my head around this scenario.

Here in my code, though the instance is of Human class. It logs "i am an Animal" in the console

I have a few question regarding this:

  1. What does it even mean?

  2. What is the possible outcome?

  3. Why & when would someone do this kind of stuff?

Parent class:

public class Species
{
    public  String Shout()
    {
        return "I am an animal";
    }
}

Child class:

public class Human : Species
{
    public new String Shout()
    {
        return "I am a Human";
    }
}

Instantiation:

class Program
{
    static void Main(string[] args)
    {
        Species h = new Human();

        Console.WriteLine(h.Shout());
    }
}

Upvotes: 0

Views: 703

Answers (4)

SB8851
SB8851

Reputation: 3

As a business example, imaging you are writing a program where you need specific actions taken on an object. The object may have gone through this program before but needs to go a different route. You can set it up to use polymorphism and override the methods you need to change. For example:

Imaging a base class of ImageProcess that has an override for ProcessPicture.

ProcessPicture may do some cropping and cleanup before it's reviewed or has data pulled from it in another program. The program sends it back, but this time ProcessPicture needs to add a watermark.

In this way we can have a single program do different tasks depending on the status of the image.

Upvotes: 0

Ian H.
Ian H.

Reputation: 3919

Polymorphism is very useful if you want to efficiently use Object Oriented Programming or OOP.

Let's say that you own a zoo. Inside this zoo there are (obviously) some animals. If you would want to store them all inside one array or list, you would have to use a base type for them, in this case Animal. Now, classes that derive from our base type Animal share the same properties, therefore also the same methods.

class Animal
{
    public string Shout ()
    { 
        return "I am an animal!"; 
    }
}

Let's now declare a class for a lion.

class Lion : Animal
{
}

Even though we haven't written the Shout method inside the Lion class, instances of Lion will also have the Shout method available to them, since they derive from the Animal class.

But what if we want the Lion class to Shout something different? We can make use of the virtual and override keywords. These can be used on properties and methods. virtual means the method or property can be overridden, while override performs the actual override. Both need to be set the right place for this to work.

To override our Shout method, we will have to mark it as virtual first.

public virtual string Shout () { ... }

Now, in our Lion class, we can perform an override on the Shout method.

public override string Shout ()
{
    return "Rooooaaar, I am a lion!";
}

Now that we clarified this, let's look at some usage of it.


Lion lion1 = new Lion();

This creates a new instance of the Lion class by calling the class' constructor. If we call lion1.Shout() now, we would get "Rooooaaar, I am a lion!" as the returned value.

Animal animal1 = new Lion();

This works as well! Since our Lion class derives from the base type Animal, the object can be stored inside an object of the type Animal. But don't be fooled! If we call animal1.Shout() now, we would still get "Rooooaaar, I am a lion!" returned.

Animal animal2 = new Animal();

This would just be an instance of the base class, meaning that the method animal2.Shout() would return "I am an animal!".


Let's now say that we have some more animals, Cat, Dog, and Lion. Without using polymorphism, we couldn't store them inside a single array, since they have nothing in common! However, if they do derive from the Animal class, we can just do something like this:

List<Animal> animals = new List<Animal>();
animals.Add(new Cat());
animals.Add(new Dog());
animals.Add(new Lion());
animals.Add(new Animal());

All of these above would work perfectly fine!

Lastly, if you want to retrieve an element from this Animal list and you want to call some Dog-specific methods on it, you can (if it is actually a Dog object, of course) use animals[1] as Dog to convert it to a Dog object. However, if it isn't a Dog object, you would just get null back from the as operator.

Upvotes: 8

boop_the_snoot
boop_the_snoot

Reputation: 3247

What does it even mean ?

Polymorphism - Poly means many, morph means forms

Thus polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'. - Tutorials Point

What is the possible outcome and

Well as from your code:

Species h = new Human();
Console.WriteLine(h.Shout()); //calling Shout method of Species

The output will be : I am an animal

Here you are calling theShout method of Species(base parent) of Human(child) by instantiating h as of type Species.

Why & when would someone do this kind of stuff

Also from your example you can call the shout method of Human with the help of casting

Console.WriteLine(((Human)h).Shout());  //calling Shout method of Human

The output will be : I am an human.

Here I casted h as Human by doing this ((Human)h) for better readability you can also do h as Human and then you call the Shout method of Human class.

Console.WriteLine((h as Human).Shout());  //calling Shout method of Human

Check the Fiddle


PS: You should also take note of what @Willem said

You should not use new. But make Shout virtual and use override in the Shout of Human


Basically polymorphism is done to overload methods(check overriding and virtual usage) of the same name but having different datatype as parameters or different datatype by itself, within a child class, a parent class or between a child and parent

Upvotes: 2

Yair Halberstadt
Yair Halberstadt

Reputation: 6831

Not a full answer to your question, but if you want your code to display "I am a Human" do the following:

Parent class :

public class Species
{
    public virtual  String Shout()
    {
         return "I am an animal";
     }
  }

Child class :

 public class Human : Species
 {
    public override String Shout()
    {
         return "I am a Human";
     }
}

For a full answer to your questions, you should really look at a textbook or article on polymorphism.

Upvotes: 1

Related Questions