Polymorphism in Object-oriented Programming - Parametric Polymorphism

Parametric Polymorphism

Further information: Parametric polymorphism in type theory and Generic programming for a more general concept

In computer science, the term polymorphism has several different but related meanings; one of these, known as parametric polymorphism in type system theory and functional programming languages, is known as generic programming in the Object Oriented Programming Community and is supported by many languages including C++, C# and Java.

Generics allow compile-time type-safety and other benefits and/or disadvantages depending on the language's implementation.

C++ implements parametric polymorphism through templates. The use of templates requires the compiler to generate a separate instance of the templated class or function for every permutation of type parameters used with it, which can lead to code bloat and difficulty debugging. A benefit C++ templates have over Java and C# is that they allow for template metaprogramming, which is a way of evaluating some of the code at compile-time rather than run-time. However, since C++ allows templates to be specialized so they behave differently when used with different types, parametricity is not enforced..

Java parametric polymorphism is called generics and implemented through type erasure. This design decision was made to ensure backwards compatibility and ensure that Java generics are interoperable with non-generic code.

C# parametric polymorphism is called generics and implemented by reification, making C# the only language of the three which supports parametric polymorphism as a first class member of the language. This design choice is leveraged to provide additional functionality, such as allowing reflection with preservation of generic types, as well as alleviating some of the limitations of erasure (such as being unable to create generic arrays). This also means that there is no performance hit from runtime casts and normally expensive boxing conversions. When primitive and value types are used as generic arguments, they get specialized implementations, allowing for efficient generic collections and methods.

Read more about this topic:  Polymorphism In Object-oriented Programming