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?
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
}
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