Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the example of polymorphism?

I kinda know what polymorphism is but failed to understand it clearly. Also my code is following:

class Human
{
   public virtual void CleanTheRoom()
   {
   }
}
class Woman:Human
{
   public override void CleanTheRoom()
   {
     //women clean faster
   }
}
class Man:Human
{
   public override void CleanTheRoom()
   {
     //men clean slower, different code here
   }
}
class Child:Human
{
   public override void CleanTheRoom()
   {
     //empty ... children are lazy :)
   }
}

Should I explain this is polymorhism because all derived classes from base class Human contain method CleanTheRoom but each of them it implements differently?

like image 949
Miria Avatar asked Apr 04 '11 19:04

Miria


1 Answers

The benefit of polymorphism comes when you want to invoke the method CleanTheRoom() on some type of Human, but you don't care which one specifically.

By having CleanTheRoom() defined at the base class level, Human, you can write shorter, cleaner code elsewhere in your application whenever you are working with an instance of Human, whether it be a Man, Woman, or Child.

Polymorphism, for example, lets you avoid ugly conditional statements where you explicitly check for each type of Human and call a different method:

Good:

private void SomeMethod(Human h)
{
    //some logic
    h.CleanTheRoom();
    //more logic
}

Bad:

private void SomeMethod(Human h)
{
    //some logic
    if (h is Man)
        CleanRoomSlowly();
    else if (h is Woman)
        CleanRoomQuickly();
    else if (h is Child)
        GoofOff();
    //some logic
}
like image 116
wsanville Avatar answered Oct 07 '22 11:10

wsanville