User:Valharmorgulis/sandbox

Bounded polymorphism
In object oriented programming languages, polymorphism where the range of types that can be acted upon is restricted is said to exhibit Bounded polymorphism. Subtyping, which is a type of polymorphism frequently made use of in statically typed object oriented programming languages such as Java and C++, in the form of inheritance, exhibits bounded polymorphism. In subtyping, an object that is a sub-type of T can act on type T and it's sub-types only. The below C++ code gives an example of subtyping and shows the bounded polymorphism it exhibits. In the above code, though the variable  declared in function main is assigned an object of it's subclass namely , it cannot execute the method   because the type of variable   is   which does not contain the method. This check for the type a variable to make sure it can do some task is bounded polymorphism.

Unbounded polymophism
Modern dynamically typed programming languages typically exhibit unbounded polymorphism where if an object is able to respond to a particular method, then it will respond to that method irrespective of it's type. This is also referred to as duck typing. In the below ruby code, the objects,   and   implement the   method and when the   method gets called by passing objects of the three different classes, the   method gets called as all of them can respond to it. There is no type checking here as compared to the C++ example provided above under bounded polymorphism.

Unbounded polymorphism vs subtyping
The advantages of unbounded polymorphism or duck typing is that the code is more concise and readable. There are certain languages like Ruby that implement common methods like length on all types which means the programmer does not have to worry whether an object will respond to it or not. The disadvantage is that the programmer has to be more careful while writing code because if an object does not respond to a method call, there is a runtime error and he/she would have to debug it.

Similarly, for subtyping, there is more protection in the form of static type checking during compile time, but the usage is restricted to the super class and it's sub types. The code tends to become less readable as compared to programming languages that exhibit unbounded polymorphism and the user has to know the nuances of the language to understand exactly what is happening.