World Library  
Flag as Inappropriate
Email this Article

Polymorphism in object-oriented programming

Article Id: WHEBN0000024930
Reproduction Date:

Title: Polymorphism in object-oriented programming  
Author: World Heritage Encyclopedia
Language: English
Subject: Class (computer programming), Design Patterns, ObjectPAL, Object-relational database, C++, Phoenix Object Basic, Standard Template Library, Template method pattern, Multiple dispatch, Type system
Publisher: World Heritage Encyclopedia

Polymorphism in object-oriented programming

In programming languages, polymorphism is the provision of a single interface to entities of different types.[1] A polymorphic type is a type whose operations can also be applied to values of some other type, or types.[2] There are several fundamentally different kinds of polymorphism:

  • If a function denotes different and potentially heterogeneous implementations depending on a limited range of individually specified types and combinations, it is called ad hoc polymorphism. Ad hoc polymorphism is supported in many languages using function overloading.
  • If the code is written without mention of any specific type and thus can be used transparently with any number of new types, it is called parametric polymorphism. In the object-oriented programming community, this is often called generic programming.
  • In object-oriented programming, subtyping or inclusion polymorphism is a concept wherein a name may denote instances of many different classes as long as they are related by some common superclass.[3]

Interaction between parametric polymorphism and subtype polymorphism leads to the concepts of variance and bounded quantification.


Ad hoc polymorphism and parametric polymorphism were originally described in Fundamental Concepts in Programming Languages, a set of lecture notes written in 1967 by British computer scientist Christopher Strachey.[4] In a 1985 paper, Peter Wegner and Luca Cardelli introduced the term inclusion polymorphism (from Greek πολύς, polus, "many, much" and μορφή, morphē, "form, shape") to model subtypes and inheritance.[2] However, implementations of subtyping and inheritance predate the term 'inclusion polymorphism', having appeared with Simula in 1967.

Kinds of polymorphism

Ad hoc polymorphism

Main article: Ad hoc polymorphism

Chris Strachey[4] chose the term ad hoc polymorphism to refer to polymorphic functions which can be applied to arguments of different types, but which behave differently depending on the type of the argument to which they are applied (also known as function overloading or operator overloading). The term "ad hoc" in this context is not intended to be pejorative; it refers simply to the fact that this type of polymorphism is not a fundamental feature of the type system. In the example below, the Add functions seems to work generically over various types when looking at the invocations, but are considered to be two entirely distinct functions by the compiler for all intents and purposes:

program Adhoc;
function Add( x, y : Integer ) : Integer;
    Add := x + y
function Add( s, t : String ) : String;
    Add := Concat( s, t )
    Writeln(Add(1, 2));
    Writeln(Add('Hello, ', 'World!'));

In dynamically typed languages the situation can be more complex as the correct function that needs to be invoked might only be determinable at run time.

Parametric polymorphism

Parametric polymorphism allows a function or a data type to be written generically, so that it can handle values identically without depending on their type.[5] Parametric polymorphism is a way to make a language more expressive, while still maintaining full static type-safety.

John C. Reynolds (and later Jean-Yves Girard) formally developed this notion of polymorphism as an extension to lambda calculus (called the polymorphic lambda calculus, or System F).

The concept of parametric polymorphism applies to both data types and functions. A function that can evaluate to or be applied to values of different types is known as a polymorphic function. A data type that can appear to be of a generalized type (e.g., a list with elements of arbitrary type) is designated polymorphic data type like the generalized type from which such specializations are made.

Parametric polymorphism is ubiquitous in functional programming, where it is often simply referred to as "polymorphism". The following example shows a parametrized list data type and two parametrically polymorphic functions on them:

data List a = Nil | Cons a (List a)
length :: List a -> Integer
length Nil         = 0
length (Cons x xs) = 1 + length xs
map :: (a -> b) -> List a -> List b
map f Nil         = Nil
map f (Cons x xs) = Cons (f x) (map f xs)

Parametric polymorphism is also available in several object-oriented languages, where it often goes under the name "generics" or "templates" (C++ and D):

class List {
    class Node {
        T elem;
        Node next;
    Node head;
    int length() { ... }
List map(Func f, List xs) {

Any parametrically polymorphic function is necessarily restricted in what it can do, working on the shape of the data instead of its value, leading to the concept of parametricity.


Main article: Subtyping

Some languages employ the idea of subtyping to restrict the range of types that can be used in a particular case of polymorphism. In these languages, subtype polymorphism (sometimes referred to as inclusion polymorphism or dynamic polymorphism) allows a function to be written to take an object of a certain type T, but also work correctly if passed an object that belongs to a type S that is a subtype of T (according to the Liskov substitution principle). This type relation is sometimes written S <: T. Conversely, T is said to be a supertype of S—written T :> S.

For example, if Number, Rational, and Integer are types such that Number :> Rational and Number :> Integer, a function written to take a Number will work equally well when passed an Integer or Rational as when passed a Number. The actual type of the object can be hidden from clients into a black box, and accessed via object identity. In fact, if the Number type is abstract, it may not even be possible to get your hands on an object whose most-derived type is Number (see abstract data type, abstract class). This particular kind of type hierarchy is known—especially in the context of the Scheme programming language—as a numerical tower, and usually contains many more types.

Object-oriented programming languages offer subtyping polymorphism using subclassing (also known as inheritance). In typical implementations, each class contains what is called a virtual table—a table of functions that implement the polymorphic part of the class interface—and each object contains a pointer to the "vtable" of its class, which is then consulted whenever a polymorphic method is called. This mechanism is an example of:

  • late binding, because virtual function calls are not bound until the time of invocation, and
  • single dispatch (i.e., single-argument polymorphism), because virtual function calls are bound simply by looking through the vtable provided by the first argument (the this object), so the runtime types of the other arguments are completely irrelevant.

The same goes for most other popular object systems. Some, however, such as Common Lisp Object System, provide multiple dispatch, under which method calls are polymorphic in all arguments.

In the following example we make cats and dogs subtypes of animals. The procedure write accepts an animal, but will also work correctly if a subtype is passed to it:

abstract class Animal {
    String talk();
class Cat extends Animal {
    String talk() { return "Meow!"; }
class Dog extends Animal {
    String talk() { return "Woof!"; }
public class MyClass {
    public static void write(Animal a) {
    public static void main() {
        write(new Cat());
        write(new Dog());

See also


External links

  • C++ examples of polymorphism
  • Objects and Polymorphism (Visual Prolog)
This article was sourced from Creative Commons Attribution-ShareAlike License; additional terms may apply. World Heritage Encyclopedia content is assembled from numerous content providers, Open Access Publishing, and in compliance with The Fair Access to Science and Technology Research Act (FASTR), Wikimedia Foundation, Inc., Public Library of Science, The Encyclopedia of Life, Open Book Publishers (OBP), PubMed, U.S. National Library of Medicine, National Center for Biotechnology Information, U.S. National Library of Medicine, National Institutes of Health (NIH), U.S. Department of Health & Human Services, and, which sources content from all federal, state, local, tribal, and territorial government publication portals (.gov, .mil, .edu). Funding for and content contributors is made possible from the U.S. Congress, E-Government Act of 2002.
Crowd sourced content that is contributed to World Heritage Encyclopedia is peer reviewed and edited by our editorial staff to ensure quality scholarly research articles.
By using this site, you agree to the Terms of Use and Privacy Policy. World Heritage Encyclopedia™ is a registered trademark of the World Public Library Association, a non-profit organization.

Copyright © World Library Foundation. All rights reserved. eBooks from World eBook Library are sponsored by the World Library Foundation,
a 501c(4) Member's Support Non-Profit Organization, and is NOT affiliated with any governmental agency or department.