Jakub Gause Jakub Gause - 7 months ago 27
C# Question

Polymorphism and Inheritance definitions in C#

I am trying to learn about main pillars of OOP.
When I was reading Inheritance definition in Microsoft docs. there were this part:

Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes.

From : https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/inheritance

All from this is clear to me but,
My question is: Isn't part of this definition: "modify the behavior that is defined in other claeses", already Polymorphism?

As Polymorphism is basically said changing behavior of derived classes on same method call. In other words, when you call method Speak(), and you have derived classes Dog and Cat from Animal base class, both derived classes will perform different action on overridden Speak() method.

Thank you for answers. :)

Answer Source

You thinking is correct. Inheritance and Polymorphism go hand in hand but they are not the same thing. Polymorphism can be a result of inheritance but not always, one can exist without the other.

In the definition, the "...modify the behavior that is defined in other classes." in my view refers to polymorphism which can be static (overloading) or dynamic (overriding). The example you gave about the Speak() method is dynamic polymorphism. You can declare the Speak() method as virtual or abstract (which will make the whole class abstract) in the Animal class and override it in the Cat and Dog sub-classes using the "override" keyword thereby changing the Speak() behavior that is defined in Animal, which is what the definition says. Check this link: https://www.tutorialspoint.com/csharp/csharp_polymorphism.htm

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download