I know that this question has been done to death at StackOverflow and that there are numerous questions posted on this already. I’ve probably read every one of them and yet, there’s this niggling doubt: I think I understand Overloading pretty well, and Overriding. What gets me is Polymorphism.
For example, the accepted answer to this question explains this with shape.Draw(). I’m confused as to how this is different from Overriding (other times I’m confused with how it is different from Overloading).
Also – does Polymorphism inherently mean deriving from an abstract class? (I think almost all the answers I’ve read on the topic uses an abstract animal class and makes a cat and a dog meow/bark 🙂
To sum up, my questions are:
-
What is Polymorphism w.r.t. Overloading and Overriding?
-
Could somebody please explain Polymorphism without an abstract class – thanks!
-
Overloading/Overriding are not subtypes of Polymorphism, are they?
Edited to add a 3rd question and modify the 2nd question.
To answer your questions:
Here’s an example with polymorphism happening with no abstract classes involved.
Polymorphism in class
Coccurs becauseSomeStaticmethod could be call with a Reference to A object or a Reference to B object. If it’s called with a reference to A,A‘samethod will be called. If it’s called with a reference to B,B‘samethod will be called. This ability of changing, on runtime, the actual method being called is called Polymorphism.Overloading barely has anything to do with Polymorphism. In fact, you can hace overloading with no inheritance involved if you want. You could even have overloading with no object orientation involved. Overloading is just letting two function to exist with the same name but with different parameters.
Overriding on the other hand, is just re-defining a method on a specialized (inherited) class. Overriding a method is necessary for polymorphism to happen. Otherwise, the would be no DUAL POSSIBILITIES on runtime (take a close look at the example).
Class C is the key to understand it all:
Poly: comes from greek. Means many.
Morph: comes from greek. Means form.
So in Polymorphism there are “many” (poly) “forms” (morph) of calling a method. Which one will be called, depends on the object being used to call the method.