Polymorphism (computer science) Not to be confused with Polymorphic code.

2 Types of polymorphism

In programming languages and type theory, polymorphism (from Greek πολύς, polys, “many, much” and μορφή, morphē, “form, shape”) is the provision of a single interface to entities of different types.[1] A polymorphic type is one whose operations can also be applied to values of some other type, or types.[2] There are several fundamentally different kinds of polymorphism:

2.1 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 seem 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:

• Ad hoc polymorphism: when a function denotes different and potentially heterogeneous implementations depending on a limited range of individually specified types and combinations. Ad hoc polymorphism is supported in many languages using function overloading. • Parametric polymorphism: when code is written without mention of any specific type and thus can be used transparently with any number of new types. In the object-oriented programming community, this is often known as generics or generic programming. In the functional programming community, this is often simply called polymorphism.

program Adhoc; function Add( x, y : Integer ) : Integer; begin Add := x + y end; function Add( s, t : String ) : String; begin Add := Concat( s, t ) end; begin Writeln(Add(1, 2)); (* Prints “3” *) Writeln(Add('Hello, ', 'World!')); (* Prints “Hello, World!" *) end.

• Subtyping (also called subtype polymorphism or inclusion polymorphism): when a name denotes instances of many different classes related by some common superclass.[3] In the object-oriented programming community, this is often simply referred to as polymorphism.

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”.[5]

The interaction between parametric polymorphism and subtyping leads to the concepts of variance and bounded quantification. 2.2

Parametric polymorphism

Main article: Parametric polymorphism

1

History

Parametric polymorphism allows a function or a data type values Ad hoc polymorphism and parametric polymorphism to be written generically, so that it can handle [6] uniformly without depending on their type. Parametric were originally described in Fundamental Concepts in Programming Languages, a set of lecture notes written polymorphism is a way to make a language more expresin 1967 by British computer scientist Christopher Stra- sive, while still maintaining full static type-safety. chey.[4] In a 1985 paper, Peter Wegner and Luca Cardelli The concept of parametric polymorphism applies to both introduced the term inclusion polymorphism to model data types and functions. A function that can evaluate subtypes and inheritance.[2] However, implementations to or be applied to values of different types is known of subtyping and inheritance predate the term “inclusion as a polymorphic function. A data type that can appear polymorphism”, having appeared with Simula in 1967. to be of a generalized type (e.g., a list with elements of 1

2

3 IMPLEMENTATION ASPECTS

arbitrary type) is designated polymorphic data type like types such that Number :> Rational and Number :> Intethe generalized type from which such specializations are ger, a function written to take a Number will work equally made. well when passed an Integer or Rational as when passed Parametric polymorphism is ubiquitous in functional pro- a Number. The actual type of the object can be hidgramming, where it is often simply referred to as “poly- den from clients into a black box, and accessed via obmorphism”. The following example in Haskell shows a ject identity. In fact, if the Number type is abstract, it parametrized list data type and two parametrically poly- may not even be possible to get your hands on an object whose most-derived type is Number (see abstract data morphic functions on them: type, abstract class). This particular kind of type hierdata List a = Nil | Cons a (List a) length :: List a -> archy is known—especially in the context of the Scheme Integer length Nil = 0 length (Cons x xs) = 1 + length xs programming language—as a numerical tower, and usumap :: (a -> b) -> List a -> List b map f Nil = Nil map f ally contains many more types. (Cons x xs) = Cons (f x) (map f xs) Object-oriented programming languages offer subtype polymorphism using subclassing (also known as Parametric polymorphism is also available in several inheritance). In typical implementations, each class object-oriented languages. For instance, Templates in contains what is called a virtual table—a table of funcC++ and D, or under the name Generics in Java: tions that implement the polymorphic part of the class class List { class Node { T elem; Node interface—and each object contains a pointer to the next; } Node head; int length() { ... } } List “vtable” of its class, which is then consulted whenever a polymorphic method is called. This mechanism is an map(Func f, List xs) { ... } example of: 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). 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.

2.3

• 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 this object), so the runtime types of the other arguments are completely irrelevant.

Subtyping

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 Some languages employ the idea of subtyping (also called polymorphic in all arguments. 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 al- 2.4 Polytypism lows a function to be written to take an object of a certain type T, but also work correctly if passed an object Main article: Generic programming § Functional lanthat belongs to a type S that is a subtype of T (according guages to the Liskov substitution principle). This type relation is sometimes written S <: T. Conversely, T is said to be a A related concept is polytypism (or data type genericity). supertype of S—written T :> S. Subtype polymorphism is A polytypic function is more general than polymorphic, usually resolved dynamically (see below). and in such a function, “though one can provide fixed ad Main article: Subtyping

In the following example we make cats and dogs subtypes hoc cases for specific data types, an ad hoc combinator is [7] of animals. The procedure letsHear() accepts an animal, absent”. but will also work correctly if a subtype is passed to it: abstract class Animal { abstract String talk(); } class Cat extends Animal { String talk() { return “Meow!"; 3 Implementation aspects } } class Dog extends Animal { String talk() { return “Woof!"; } } void letsHear(Animal a) { println(a.talk()); 3.1 Static and dynamic polymorphism } void main() { letsHear(new Cat()); letsHear(new Dog()); } Main articles: Static polymorphism, Late binding and Dynamic dispatch In another example, if Number, Rational, and Integer are

3 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, as 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, 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.

4

See also • Type theory • Duck typing for polymorphism without (static) types • Polymorphic code (Computer virus terminology) • System F for a lambda calculus with parametric polymorphism. • Type class • Virtual inheritance

5

References

[1] Bjarne Stroustrup (February 19, 2007). “Bjarne Stroustrup’s C++ Glossary”. polymorphism - providing a single interface to entities of different types. [2] Cardelli, Luca; Wegner, Peter (December 1985). “On understanding types, data abstraction, and polymorphism” (PDF). ACM Computing Surveys (New York, NY, USA: ACM) 17 (4): 471–523. doi:10.1145/6041.6042. ISSN 0360-0300.: “Polymorphic types are types whose operations are applicable to values of more than one type.” [3] Booch, et all 2007 Object-Oriented Analysis and Design with Applications. Addison-Wesley. [4] C. Strachey - Fundamental Concepts in Programming http://www.itu.dk/courses/BPRD/E2009/ Languages fundamental-1967.pdf

[5] Allen B. Tucker (28 June 2004). Computer Science Handbook, Second Edition. Taylor & Francis. pp. 91–. ISBN 978-1-58488-360-9. [6] Pierce, B. C. 2002 Types and Programming Languages. MIT Press. [7] Ralf Lammel and Joost Visser, “Typed Combinators for Generic Traversal”, in Practical Aspects of Declarative Languages: 4th International Symposium (2002), p. 153.

6 External links • C++ examples of polymorphism • Objects and Polymorphism (Visual Prolog)

4

7 TEXT AND IMAGE SOURCES, CONTRIBUTORS, AND LICENSES

7

Text and image sources, contributors, and licenses

7.1

Text

• Polymorphism (computer science) Source: https://en.wikipedia.org/wiki/Polymorphism_(computer_science)?oldid=678319758 Contributors: Ed Poor, Edward, Michael Hardy, TakuyaMurata, Delirium, Minesweeper, Ahoerstemeier, Kragen, LittleDan, Charles Matthews, Dysprosia, Greenrd, Furrykef, Wernher, Bevo, Dbabbitt, Aluion, Robbot, Korath, RedWolf, Wlievens, Tobias Bergemann, BenFrantzDale, Peter Bailey, Noone~enwiki, Esap, Daniel Brockman, Neilc, Uranographer, Maximaximax, Gauss, Abdull, Pasd, Deebster, Ta bu shi da yu, Bedders, Leibniz, Hydrox, Mjpieters, Demitsu, Paul August, Cyclopia, Clement Cherlin, Spayrard, Indil, Edward Z. Yang, Spalding, AshtonBenson, Phyzome, Orimosenzon, ABCD, Wtmitchell, MIT Trekkie, Forderud, Kendrick Hang, Crosbiesmith, Simetrical, Ruud Koot, Jeff3000, Davidfstr, Notanotheridiot, Marudubshinki, BD2412, Qwertyus, Anarchivist, Kbdank71, .digamma, NeonMerlin, Cjoev, Seliopou, VKokielov, TheMidnighters, Thomas Linder Puls, RexNL, Metropolitan90, Bgwhite, YurikBot, Hairy Dude, FrenchIsAwesome, Amshali, Gaius Cornelius, Stassats, DeadEyeArrow, Mrxcol, Searchme, GraemeL, JoanneB, LeonardoRob0t, TuukkaH, Yakudza, SmackBot, Blurgk~enwiki, Vald, AutumnSnow, PizzaMargherita, BiT, Sam Pointon, Gilliam, Chris the speller, Bluebot, Timneu22, Clconway, Nbarth, NYKevin, Wesw02, T00h00, Radagast83, Nakon, Drc79, Zahid Abdassabur, Albert cheng, Antonielly, Avodaemon, Beetstra, Boomshadow, Wikidrone, Larrymcp, Ryulong, DabMachine, Iridescent, Dakart, Amakuru, MightyWarrior, Sayres, FatalError, Ahy1, TicketMan, Torc2, Ayzmo, Shawn wiki, Wainson, Tmopkisn, Altamel, JAnDbot, Wmbolle, Magioladitis, VoABot II, Midgrid, DerHexer, Joshisachin79, Gwern, Verdatum, Kschidam, Katalaveno, Daniel5Ko, Doug4, Useight, Remi0o, VolkovBot, TXiKiBoT, Raymondwinn, Gtkenny, Synthebot, Aeris-chan, Caulde, Flyer22, Fratrep, ZikiCZ, Classicalecon, Loren.wilton, ClueBot, AldoNadi, Adrianwn, Naveenreddy83, EtienneNavarr, Katumandu, Gendut, Jelsova, CanadianLinuxUser, Favonian, Lightbot, Jarble, Legobot, CCFS, Luckas-bot, Ptbotgourou, Max0913, Pcap, Shadoninja, Tiburondude, AnomieBOT, HairyPerry, DemocraticLuntz, Rubinbot, Killiondude, Piano non troppo, TechBot, Martnym, GrouchoBot, VladimirReshetnikov, SassoBot, WhatisFeelings?, Dougofborg, Sqrmax, FrescoBot, Pasqui23, Maggyero, DrilBot, RedBot, Joesmoe10, RjwilmsiBot, EmausBot, Faolin42, Tommy2010, Thecheesykid, AvicAWB, Donner60, EdoBot, TitaniumCarbide, ClueBot NG, Baartvaark, BG19bot, Dexbot, AltF4ToWin, Konnerjr, François Robere, Ugog Nizdast, Lesser Cartographies, Uk1211, ChiTownDev and Anonymous: 252

7.2

Images

7.3

Content license

• Creative Commons Attribution-Share Alike 3.0

Polymorphism (computer science) -

hoc cases for specific data types, an ad hoc combinator is absent”.[7] ... duck typing, and a dynamically linked library may oper- ate on objects without knowing ...

54KB Sizes 5 Downloads 163 Views

Recommend Documents

The Future of Computer Science - Cornell Computer Science
(Cornell University, Ithaca NY 14853, USA). Abstract ... Where should I go to college? ... search engine will provide a list of automobiles ranked according to the preferences, .... Rather, members of a community, such as a computer science.

Computer Science E-259 Lectures - Computer Science E-259: XML ...
Sep 17, 2007 - most important new technology development of the last two years." Michael Vizard ... applications: what are the tools and technologies necessary to put ... XML. When. ▫ The World Wide Web Consortium (W3C) formed an XML.

Computer Science E-259
Jan 7, 2008 - Yahoo! UI Library http://developer.yahoo.com/yui/ ..... how to program in JavaScript and PHP, how to configure. Apache and MySQL, how to ...

Computer Science E-259
Nov 19, 2007 - labeling the information content of diverse data sources .... .... ELEMENT article (url, headline_text, source, media_type, cluster,.

TEXTS IN COMPUTER SCIENCE
Java — Designed as a language to support mobile programs, Java has special .... We offer a few low-level coding hints that are helpful in building quality programs. ...... cheap in selecting your table size or else you will pay the price later.

Computer Science E-259
Oct 1, 2007 - DOCTYPE students SYSTEM "student.dtd">.

Computer Science E-259
Nov 29, 2007 - these foundations, the course will explore in detail a number of case studies that utilize XML in e-business: e-commerce, web personalization, ...

Computer Science E-259
Oct 1, 2007 - By Definition. ▫ The result of parsing a document with a DOM parser is a. DOM tree that matches the structure of that document. ▫ After parsing is ...

COMPUTER SCIENCE - Pune University
Poona College of Arts, Science and Commerce, Pune 411 001. 7. 001. 070 ... Sinhagad Technical Education Society's B.C.S. College, Pune 411 041.( 878-.

Computer Science E-259
Dec 3, 2007 - Redefines simple and complex types, groups, and attribute groups from an external schema redefine. Describes the format of non-XML data ...

BS Computer Science - GCUF
Nov 1, 2015 - GOVERNMENT COLLEGE UNIVERSITY, FAISALABAD. 2nd MERIT LIST OF BS Computer Science (EVENING). FOR FALL, 2015-2016.

Computer Science E-259
Nov 19, 2007 - ELEMENT article (url, headline_text, source, media_type, cluster, tagline, document_url ... http://www.oasis-open.org/specs/index.php#dbv4.1.

Computer Science E-259
Oct 22, 2007 - Computer Science E-259. XML with Java. Lecture 5: ... XPath 1.0. ▫ Location Paths. ▫ Data Types ... Data Types. ▫ boolean. ▫ number. ▫ string.

Computer Science E-259
Nov 29, 2007 - students with previous Java programming and web development experience, this course introduces XML as a key enabling technology in today's e-business applications. Students will learn the fundamentals of XML: schemas, XSL stylesheets,

Computer Science E-259
Oct 22, 2007 - 6. Copyright © 2007, David J. Malan . All Rights Reserved. XSLT 1.0, Continued. Data Types. ▫ boolean. ▫ number. ▫ string. ▫ node-set. ▫ external object. ▫ result tree fragment ...

Computer Science E-259
Jan 7, 2008 - . 4019 2445 .... with SQL, and how to use Ajax with both XML and JSON. The course ...

Computer Science E-259
Oct 1, 2007 - structure and content of an XML document. ▫ SAX does this by the type and order of events that are invoked. ▫ DOM does this by using objects in ...

BS Computer Science - GCUF
Nov 1, 2015 - GOVERNMENT COLLEGE UNIVERSITY, FAISALABAD. 2nd MERIT LIST OF BS Computer Science (EVENING). FOR FALL, 2015-2016.

TEXTS IN COMPUTER SCIENCE
thousand bright students, so look there for errata and revised solutions. ..... content, just like the house numbers on a street permit access by address, not ...

pdf-1466\communication-networks-computer-science-computer ...
... of the apps below to open or edit this item. pdf-1466\communication-networks-computer-science-computer-networking-by-cram101-textbook-reviews.pdf.