Object-oriented – Is duck typing a subset of polymorphism

duck-typingobject-orientedpolymorphism

From Polymorphism on WIkipedia

In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface.

From duck typing on Wikipedia

In computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface.

My interpretation is that based on duck typing, the objects methods/properties determine the valid semantics. Meaning that the objects current shape determines the interface it upholds.

From polymorphism you can say a function is polymorphic if it accepts multiple different data types as long as they uphold an interface.

So if a function can duck type, it can accept multiple different data types and operate on them as long as those data types have the correct methods/properties and thus uphold the interface.

(Usage of the term interface is meant not as a code construct but more as a descriptive, documenting construct)

  • What is the correct relationship between ducktyping and polymorphism ?
  • If a language can duck type, does it mean it can do polymorphism ?

Best Answer

I say that polymorphism is a generic trait, that can be implemented several ways:

  • class based inheritance.
  • prototype based objects (with or without inheritance)
  • duck typing
  • interface compliance (as done by Go's interfaces and implicitly on C++ templates)

each of them allows the programmer to use a single code with different types, so all embody the concept of polymorphism.