Confusion with polymorphism: Parametric, Inclusion, Coercion, and Overloading

萝らか妹 提交于 2019-12-24 12:33:43

问题


Reading stackoverflow questions, the general consensus seems to be that overloading is not part of polymorphism.

However, my OOP lecture notes state that:

"There are four kinds of polymorphism: Parametric, Inclusion, Coercion, and Overloading".

In the notes, it refers to overloading with methods with different parameters, and also overloading operators, e.g. + in the sense of ints and floats.

Wikipedia also states "Ad hoc polymorphism is supported in many languages using function overloading."

Thus i'm confused as to why people say this isn't part of polymorphism, as it seems to be in my opinion; we have different forms for one method.

Could anyone elaborate?

Thanks.


回答1:


If you take a strict definition of what the word Poly-Morphism means, then yes, overloading is polymorphism. The methods have the same name, different signatures and the runtime knows which method to use based upon the signature you use. That's many forms of the same method. It is not "classic" descriptions of polymorphism with classes and inheritance, animals, dogs, and cats, etc. Some languages have operator overloading. Is that many forms of the same type?

It really depends on what you say is polymorphing. If you say that many forms only relates to objects, they yeah, you can't have overloading as "real" polymorphism in the OOP sense because they are methods, not objects.

This can help, Polymorphism vs Overriding vs Overloading

You can see there are many opinions.




回答2:


Ad hoc polymorphism is considering the operators themselves to be like objects, which can be overloaded, yet still work in situations where the user is unaware of the specifics of the overload. This is basically the same as the motivation for polymorphism in objects, except with operators. http://en.wikipedia.org/wiki/Operator_overloading



来源:https://stackoverflow.com/questions/23971119/confusion-with-polymorphism-parametric-inclusion-coercion-and-overloading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!