0

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://learn.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. :)

Jakub Gause
  • 309
  • 3
  • 10
  • 1
    Possible duplicate of [what's the difference between inheritance and polymorphism?](https://stackoverflow.com/questions/7325518/whats-the-difference-between-inheritance-and-polymorphism) – mjwills Aug 17 '17 at 10:16

1 Answers1

0

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

  • Now it is clearer to me :), but one thing I don't understand, as you mention polymorphims and inheritance are two different things, I agree with that, but what I am not sure about, is that part: "one can exist without the other", Inheritance sure (just basic method that is not overriden), but how can Polymorphism exist without inheritance?, only what comes to my mind is when we would consider Static polymorphism as you mentioned, but Dynamic Polymorphism is not possible without Inheritance or am I wrong? – Jakub Gause Aug 17 '17 at 16:00
  • Polymorphism as an OOP concept is very broad and not limited to these two, check out other types here: https://en.wikipedia.org/wiki/Polymorphism_(computer_science). But you are right, this type of polymorphism (overriding) does require inheritance in C#. But in general, polymorphism is possible without inheritance, e.g. in other languages like python: https://dzone.com/articles/polymorphism-and-inheritance – Sphelele Zondo Aug 17 '17 at 18:11