Search code examples
polymorphismadhoc

Polymorphism, Parametric Polymorphism, Ad Hoc Polymorphism


I'm trying to find out the differences between these types of polymorphism. I can't find much material on Ad-Hoc Polymorphism.

I want to say that Polymorphism is Parametric Polymorphism but is generally just referred to as Polymorphism? Am I correct to assume this?

I know that polymorphism can be used in inheritance but I'm not sure what other properties it can serve.

If anyone could help define these types of polymorphism and maybe try give the distinct differences, that would be great.

Thank you!

Note: An example of each in Python would be great.


Solution

  • Polymorphism is the general concept. Ad-hoc polymorphism and parametric polymorphism are specializations of the concept. (According to the relevant Wikipedia article, there also exist other types of polymorphism.)

    Ad-hoc polymorphism is also known as function overloading, and it refers to using the type system in order to resolve precisely which method will be invoked. So, we may have two functions, both called fn, where one accepts an int parameter, while the other accepts a String parameter, and the right function to invoke is chosen based on the type of parameter being passed.

    Parametric polymorphism is basically the use of generics. So, the Collection<T> interface can be said to be polymorphic because it can be used as Collection<Integer> and as Collection<String> and what not. The name "parametric" refers to the presence of generic parameters.

    As far as I know, python does not have a strong concept of types, and neither does it support generics, ("templates" in C++ parlance,) so these concepts are probably inapplicable to Python. But, I have no practical experience with Python, so I may be wrong. Perhaps someone else can enlighten us.