Jump to content

Polymorphism in object-oriented programming: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
m "ad-hoc" -> "ad hoc"
Ruud Koot (talk | contribs)
Line 1: Line 1:
#REDIRECT [[Polymorphism (computer science)]]
{{Disputed|date=October 2010}}
{{merge to|Polymorphism (computer science)|date=April 2011}}
{{Polymorphism}}
[[Subtype]] polymorphism, often referred to as simply '''polymorphism''' in the context of [[object-oriented programming]], is the ability to create a variable, a function, or an object that has more than one form. In principle, polymorphism can arise in other computing contexts and shares important similarities with the concept of [[degeneracy (biology)|degeneracy]] in biology.

The purpose of polymorphism is to implement a style of programming called ''[[Message_passing|message-passing]]'', in which objects of various types define a common interface of operations for users. In [[strong typing|strongly typed]] languages, polymorphism usually means that type A somehow derives from type B, or type C implements an interface that represents type B. In [[weak typing|weakly typed]] languages, types are implicitly polymorphic.

[[Operator overloading]] of the numeric operators (+, -, *, and /) allows polymorphic treatment of the various numerical types: integer, unsigned integer, float, decimal, etc.; each of which have different ranges, bit patterns, and representations. Another common example is the use of the "+" operator which allows similar or polymorphic treatment of numbers (addition), strings (concatenation), and lists (attachment). This is a lesser used feature of polymorphism.

The primary usage of polymorphism in industry ([[object-oriented programming]] theory) is the ability of [[Object (computer science)|objects]] belonging to different types to respond to [[Method (computer science)|method]], [[field (computer science)|field]], or [[property (computer science)|property]] calls of the same name, each one according to an appropriate type-specific behavior.

The different objects involved only need to present a compatible [[Interface (computer science)|interface]] to the clients' ([[Subroutine|calling routines]]). That is, there must be public or internal methods, fields, events, and properties with the same name and the same [[Parameter (computer science)|parameter sets]] in all the [[Superclass (computer science)|superclasses]], [[subclass (computer science)|subclass]]es and interfaces. In principle, the object types may be unrelated, but since they share a common interface, they are often implemented as [[Subclass (computer science)|subclasses]] of the same superclass. Though it is not required, it is understood that the different methods will also produce similar results (for example, returning values of the same type).

Polymorphism (which is strictly referring to subtype polymorphism in the context of this article) is not the same as [[method overloading]] or [[method overriding]]<ref name="headfirstjava">{{cite book |last=Sierra|first=Kathy|coauthors=Bert Bates|title=Head First Java, 2nd Ed.|publisher=[[O'Reilly Media, Inc.]]|year=2005|isbn=0-596-00920-8}}</ref> (which is known instead as ''ad hoc'' polymorphism<ref name="lucac">[http://lucacardelli.name/Papers/OnUnderstanding.A4.pdf "On Understanding Types, Data Abstraction, and Polymorphism"]</ref>). Polymorphism is only concerned with the application of specific [[implementation]]s to an [[interface (object-oriented programming)|interface]] or a more generic base class. Method overloading refers to methods that have the same name but different signatures inside the same class. Method overriding is where a subclass replaces the implementation of one or more of its parent's methods. Neither method overloading nor method overriding is by itself an implementation of polymorphism.<ref name="tcpl">
{{cite book
| last = Stroustrup
| first = Bjarne
| title = The C++ Programming Language Special Edition
| publisher = O'Reilly Media, Inc.
| year = 2000
| isbn = 0-201-70073-5}}
</ref>

==Parametric Polymorphism==
{{further2|[[Parametric polymorphism]] in type theory|[[Generic programming]] for a more general concept}}

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

[[Generic programming|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, [[Generic_programming#Advantages_and_disadvantages|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 (computer science)|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 [[Generic_programming#Generic_programming_in_C.23_and_.NET|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.

==Example==
Here is a simple example written in [[Python_(programming_language)|Python]].
<source lang=python>
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def talk(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")

class Cat(Animal):
def talk(self):
return 'Meow!'

class Dog(Animal):
def talk(self):
return 'Woof! Woof!'

animals = [Cat('Missy'),
Dog('Lassie')]

for animal in animals:
print(animal.name + ': ' + animal.talk())

# prints the following:
# Missy: Meow!
# Lassie: Woof! Woof!
</source>

==See also==
* [[Structural Type System]]
* [[Duck typing]]
* [[Inheritance (computer science)]]
* [[Polymorphic association]]
* [[Virtual functions]]

==References==
<references/>

==External links==
* [http://javalessons.com/cgi-bin/fun/java-tutorials-main.cgi?ses=ao789&code=ovd&sub=fun Java polymorphism interactive lesson]
* [http://wiki.visual-prolog.com/index.php?title=Objects_and_Polymorphism Objects and Polymorphism (Visual Prolog)]
* [http://www.codeproject.com/KB/cpp/PolyC.aspx Polymorphism in C]
* [http://home.comcast.net/~fbui/OOC.html Object-oriented programming in C]{{dead link|date=May 2013}}

{{DEFAULTSORT:Polymorphism In Object-Oriented Programming}}
[[Category:Polymorphism (computer science)]]
[[Category:Articles with example code]]
[[Category:Articles with example C++ code]]
[[Category:Articles with example Java code]]
[[Category:Articles with example Perl code]]
[[Category:Articles with example Python code]]
[[Category:Articles with example Racket code]]

Revision as of 16:46, 22 September 2013