Content deleted Content added
No edit summary Tag: Reverted |
No edit summary |
||
(45 intermediate revisions by 38 users not shown) | |||
Line 1:
{{Short description|
{{
{{Polymorphism}}
In [[programming language theory]] and [[type theory]], '''polymorphism''' is the approach that allows a value type to assume different types.<ref name="Luca">{{Cite journal |last1=Cardelli |first1=Luca |author1-link=Luca Cardelli |last2=Wegner |first2=Peter |author2-link=Peter Wegner (computer scientist)|doi=10.1145/6041.6042 |title=On understanding types, data abstraction, and polymorphism |journal=[[ACM Computing Surveys]] |volume=17 |issue=4 |pages=471–523 |date=December 1985 |url=http://lucacardelli.name/Papers/OnUnderstanding.A4.pdf |citeseerx=10.1.1.117.695 |s2cid=2921816}}: "Polymorphic types are types whose operations are applicable to values of more than one type."</ref>
{{cite web | url=http://www.stroustrup.com/glossary.html#Gpolymorphism | author=Bjarne Stroustrup | title=Bjarne Stroustrup's C++ Glossary | date=February 19, 2007 | quote=polymorphism – providing a single interface to entities of different types.}}</ref> or the use of a single symbol to represent multiple different types.<ref name="Luca">{{Cite journal | last1 = Cardelli | first1 = Luca| author-link1 = Luca Cardelli| last2 = Wegner | first2 = Peter| author-link2 = Peter Wegner| doi = 10.1145/6041.6042| title = On understanding types, data abstraction, and polymorphism| journal = [[ACM Computing Surveys]]| volume = 17| issue = 4| pages = 471–523| date=December 1985 | url = http://lucacardelli.name/Papers/OnUnderstanding.A4.pdf| citeseerx = 10.1.1.117.695| s2cid = 2921816}}: "Polymorphic types are types whose operations are applicable to values of more than one type."</ref>The concept is borrowed from a principle in biology where an organism or species can have many different forms or stages.<ref name="Moved">{{cite web | title=Polymorphism |work=The Java™ Tutorials: Learning the Java Language: Interfaces and Inheritance |publisher=Oracle | url=https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html | access-date=2021-09-08}}</ref>▼
▲In [[object-oriented programming]], polymorphism is the provision of one [[Interface (object-oriented programming)|interface]] to entities of different [[data type]]s.<ref>{{cite web |
The most commonly recognized major classes of polymorphism are::::::::::::;::::▼
* ''[[Ad hoc polymorphism]]'': defines a common interface for an arbitrary set of individually specified types.
* ''[[Parametric polymorphism]]'':
* ''[[Subtyping]]'' (also called ''subtype polymorphism'' or ''inclusion polymorphism''): when a name denotes instances of many different classes related by some common superclass.<ref name="gbooch">{{cite book |last1=Conallen |first1=J. |last2=Engle |first2=M. |last3=Houston |first3=K. |last4=Maksimchuk |first4=R. |last5=Young |first5=B. |last6=Booch |first6=G. |author6-link=Grady Booch |date=2007 |title=Object-Oriented Analysis and Design with Applications |publisher=Pearson Education |edition=3rd
==History==
Interest in polymorphic [[type system]]s developed significantly in the
In a 1985 paper, [[Peter Wegner (computer scientist)|Peter Wegner]] and [[Luca Cardelli]] introduced the term ''inclusion polymorphism'' to model subtypes and [[Inheritance (object-oriented programming)|inheritance]],<ref name="Luca"/> citing [[Simula]] as the first programming language to implement it.
==
===Ad hoc polymorphism===
{{
[[Christopher Strachey]] chose the term ''ad hoc polymorphism'' to refer to polymorphic functions that can be applied to arguments of different types, but that behave differently depending on the type of the argument to which they are applied (also known as [[function overloading]] or [[operator overloading]]).<ref name=Strachey00/> The term "[[ad hoc]]" in this context is not
<syntaxhighlight lang="
class AdHocPolymorphic {
public String add(int x, int y) {
return "Sum: " + (x + y);
}
public String add(String name) {
return "Added " + name;
}
public class Adhoc {
public static void main(String[] args) {
AdHocPolymorphic poly = new AdHocPolymorphic();
System.out.println(poly.add(1,2)); // prints "Sum: 3"
System.out.println(poly.add("Jay")); // prints "Added Jay"
}
}
</syntaxhighlight>
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.
[[Implicit type conversion]] has also been defined as a form of polymorphism, referred to as "coercion polymorphism".<ref name="Luca"/><ref name="Tucker2004">{{cite book |
===Parametric polymorphism===
{{
''Parametric polymorphism'' allows a function or a data type to be written generically, so that it can handle values ''uniformly'' without depending on their type.<ref name="bjpierce">{{cite book |
The concept of parametric polymorphism applies to both [[data type]]s and [[
Parametric polymorphism is ubiquitous in functional programming, where it is often simply referred to as "polymorphism". The
<syntaxhighlight lang="Haskell">
Line 63 ⟶ 66:
</syntaxhighlight>
Parametric polymorphism is also available in several object-oriented languages. For instance, [[Template (C++)|templates]] in [[C++]] and [[D (programming language)|D]], or under the name [[Generics in Java|generics]] in [[C Sharp (programming language)|C#]], [[Delphi
<syntaxhighlight lang="CSharp">
Line 83 ⟶ 86:
===Subtyping===
{{
Some languages employ the idea of ''subtyping'' (also called ''subtype polymorphism'' or ''inclusion polymorphism'') to restrict the range of types that can be used in a particular case of polymorphism. In these languages, subtyping 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 {{nowrap|''S''
In the following Java example
<syntaxhighlight lang="
abstract class
abstract String
}
class Cat extends
String
return "Meow!";
}
}
class Dog extends
String
return "Woof!";
}
}
static void letsHear(final
System.out.println(
}
Line 115 ⟶ 118:
</syntaxhighlight>
[[File:UML class pet.svg]]
In another 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 (systems)|black box]], and accessed via object [[identity (object-oriented programming)|identity]].▼
▲In another example, if ''Number'', ''Rational'', and ''Integer'' are types such that {{nowrap|''Number''
[[Object-oriented programming language]]s offer subtype polymorphism using ''[[Subclass (computer science)|subclass]]ing'' (also known as ''[[inheritance in object-oriented programming|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:▼
▲[[Object-oriented programming language]]s offer subtype polymorphism using ''[[Subclass (computer science)|subclass]]ing'' (also known as ''[[inheritance in object-oriented programming|inheritance]]''). In typical implementations, each class contains what is called a ''[[virtual table]]''
* ''[[late binding]]'', because virtual function calls are not bound until the time of invocation;
* ''[[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 <code>this</code> 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.
Line 126 ⟶ 130:
===Row polymorphism===
{{
{{see also|Duck typing}}
Row polymorphism<ref>
{{cite conference
|
|
|
|
|
|
|
</ref> is a similar, but distinct concept from subtyping. It deals with [[Structural type system|structural types]].
===Polytypism===
{{
A related concept is ''polytypism'' (or ''data type genericity''). A polytypic function is more general than polymorphic, and in such a function, "though one can provide fixed ad hoc cases for specific data types, an ad hoc combinator is absent".<ref>{{cite book |first1=Ralf |last1=Lämmel |first2=Joost |last2=Visser |chapter=Typed Combinators for Generic Traversal |title=Practical Aspects of Declarative Languages: 4th International Symposium |publisher=Springer |date=2002 |isbn=354043092X |pages=137–154, See p. 153 |citeseerx=10.1.1.18.5727 |url=}}</ref>
===Rank polymorphism===
Rank polymorphism is one of the defining features of the [[array programming]] languages, like [[APL (programming language)|APL]]. The essence of the rank-polymorphic programming model is implicitly treating all operations as aggregate operations, usable on arrays with arbitrarily many dimensions,<ref>{{cite arXiv |last1=Slepak |first1=Justin |last2=Shivers |first2=Olin |last3=Manolios |first3=Panagiotis |date=2019 |title=The semantics of rank polymorphism |class=cs.PL |eprint=1907.00509}}</ref> which is to say that rank polymorphism allows functions to be defined to operate on arrays of any shape and size.
==Implementation aspects==
===Static and dynamic polymorphism===
{{
Polymorphism can be distinguished by when the implementation is selected: statically (at compile time) or dynamically (at run time, typically via a [[virtual function]]). This is known respectively as ''[[static dispatch]]'' and ''[[dynamic dispatch]],'' and the corresponding forms of polymorphism are accordingly called ''static polymorphism'' and ''dynamic polymorphism''.
Static polymorphism executes faster, because there is no dynamic dispatch overhead, but requires additional compiler support. Further, static polymorphism allows greater static analysis by compilers (notably for optimization), source code analysis tools, and human readers (programmers). Dynamic polymorphism is more flexible but slower—for example, dynamic polymorphism allows [[Duck typing|duck typing]], and a dynamically linked library may operate on objects without knowing their full type.
Static polymorphism typically occurs in ad hoc polymorphism and parametric polymorphism, whereas dynamic polymorphism is usual for subtype polymorphism. However, it is possible to achieve static polymorphism with subtyping through more sophisticated use of [[template metaprogramming]], namely the [[curiously recurring template pattern]].
When polymorphism is exposed via a [[Library (computing)|library]], static polymorphism becomes impossible for [[dynamic libraries]] as there is no way of knowing what types the parameters are when the [[shared object]] is built. While languages like C++ and Rust use [[monomorphization|monomorphized]] templates, the [[Swift programming language]] makes extensive use of dynamic dispatch to build the [[application binary interface]] for these libraries by default. As a result, more code can be shared for a reduced system size at the cost of runtime overhead.<ref>{{cite web |last1=Beingessner |first1=Alexis |title=How Swift Achieved Dynamic Linking Where Rust Couldn't |url=https://gankra.github.io/blah/swift-abi/
==See also==
* [[Type class]]
* [[Virtual inheritance]]
==References==
{{
==External links==
Line 178 ⟶ 181:
{{DEFAULTSORT:Polymorphism}}
[[Category:Polymorphism (computer science)| ]]
[[Category:Articles with example C Sharp code]]▼
[[Category:Articles with example Haskell code]]▼
[[Category:Articles with example Java code]]▼
[[Category:Articles with example Pascal code]]▼
[[Category:Data types]]
[[Category:Functional programming]]
Line 188 ⟶ 187:
[[Category:Type theory]]
[[Category:Generic programming]]
[[Category:Programming language comparisons]]
<!-- Hidden categories below -->
▲[[Category:Articles with example C Sharp code]]
▲[[Category:Articles with example Haskell code]]
▲[[Category:Articles with example Java code]]
▲[[Category:Articles with example Pascal code]]
|