Polymorphism in object-oriented programming
Encyclopedia
Subtype polymorphism
Subtype polymorphism
In programming language theory, subtyping or subtype polymorphism is a form of type polymorphism in which a subtype is a datatype that is related to another datatype by some notion of substitutability, meaning that program constructs, typically subroutines or functions, written to operate on...

, almost universally called just polymorphism in the context of object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

, is the ability to create a variable, a function, or an object that has more than one form. The word derives from the Greek "πολυμορφισμός" meaning "having multiple forms". In principle, polymorphism can however arise in other computing contexts and it shares important similarities to the concept of degeneracy
Degeneracy (biology)
Within biological systems, degeneracy refers to circumstances where structurally dissimilar components/modules/pathways can perform similar functions under certain conditions, but perform distinct functions in other conditions. Degeneracy is thus a relational property that requires comparing the...

 in biology.

The purpose of polymorphism is to implement a style of programming called message-passing in the literature, in which objects of various types define a common interface of operations for users. In 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 weakly typed languages types are implicitly polymorphic.

Operator overloading
Operator overloading
In object oriented computer programming, operator overloading—less commonly known as operator ad-hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments...

 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
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

 theory) is the ability of objects
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...

 belonging to different types to respond to method
Method (computer science)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...

, field
Field (computer science)
In computer science, data that has several parts can be divided into fields. Relational databases arrange data as sets of database records, also called rows. Each record consists of several fields; the fields of all records form the columns....

, or property calls of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, and so the exact behavior is determined at run-time (this is called late binding
Late binding
Late binding is a computer programming mechanism in which the method being called upon an object is looked up by name at runtime. This is informally known as duck typing or name binding....

or dynamic binding
Dynamic dispatch
In computer science, dynamic dispatch is the process of mapping a message to a specific sequence of code at runtime. This is done to support the cases where the appropriate method can't be determined at compile-time...

).

The different objects involved only need to present a compatible interface
Interface (computer science)
In the field of computer science, an interface is a tool and concept that refers to a point of interaction between components, and is applicable at the level of both hardware and software...

 to the clients' (calling routines
Subroutine
In computer science, a subroutine is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code....

). That is, there must be public or internal methods, fields, events, and properties with the same name and the same parameter sets
Parameter (computer science)
In computer programming, a parameter is a special kind of variable, used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are called arguments...

 in all the superclasses, subclasses and interfaces. In principle, the object types may be unrelated, but since they share a common interface, they are often implemented as 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).

(Subtype) polymorphism is not the same as method overloading
Method overloading
Function overloading or method overloading is a feature found in various programming languages such as Ada, C#, VB.NET, C++, D and Java that allows the creation of several methods with the same name which differ from each other in terms of the type of the input and the type of the output of the...

 or method overriding , (that is known instead as ad-hoc polymorphism ). Polymorphism is only concerned with the application of specific implementation
Implementation
Implementation is the realization of an application, or execution of a plan, idea, model, design, specification, standard, algorithm, or policy.-Computer Science:...

s to an 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 are by themselves implementations of polymorphism.

Examples

Java



// from file Animal.java
package org.wikipedia.examples;

public class Animal {
public String name;

public Animal(String name) {
this.name = name;
}

public String talk {
throw new UnsupportedOperationException("Error: This function should always be overridden by child classes!");
}
}

// from file Cat.java
package org.wikipedia.examples;

public class Cat extends Animal {

public Cat(String name) {
super(name);
}

@Override
public String talk {
return "Meow!";
}
}

// from file Dog.java
package org.wikipedia.examples;

public class Dog extends Animal {

public Dog(String name) {
super(name);
}

@Override
public String talk {
return "Woof! Woof!";
}
}

// from file PolymorphismExample.java
package org.wikipedia.examples;

import java.util.*;

public class PolymorphismExample {

public static void main(String[] args) {
private Collection animals = new ArrayList;
animals.add(new Cat("Missy"));
animals.add(new Dog("Lassie"));

for (Animal a : animals) {
System.out.println(a.name + " says: " + a.talk);
}
}

}

// When you run this, the output is:
// Missy says: Meow!
// Lassie says: Woof! Woof!

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'),
Cat('Mr. Mistoffelees'),
Dog('Lassie')]

for animal in animals:
print animal.name + ': ' + animal.talk
  1. prints the following:
  2. Missy: Meow!
  3. Mr. Mistoffelees: Meow!
  4. Lassie: Woof! Woof!


Parametric Polymorphism

In computer science, the term polymorphism has several different but related meanings; one of these, known as parametric polymorphism
Parametric polymorphism
In programming languages and type theory, parametric polymorphism is a way to make a language more expressive, while still maintaining full static type-safety. Using parametric polymorphism, a function or a data type can be written generically so that it can handle values identically without...

in type system
Type system
A type system associates a type with each computed value. By examining the flow of these values, a type system attempts to ensure or prove that no type errors can occur...

 theory and functional programming languages, is known as generic programming
Generic programming
In a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...

 in the Object Oriented Programming Community and is supported by many languages including C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

, C# and Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

.

Generics
Generic programming
In a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...

 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
Template metaprogramming
Template metaprogramming is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these templates include compile-time constants, data structures, and...

, which is a way of pre-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
Type erasure
In programming languages, type erasure refers to the compile-time process by which explicit type annotations are removed from a program, before it is executed at run-time. An operational semantics that does not require programs to be accompanied by types is called a type-erasure semantics, to be...

. 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
Reification (computer science)
Reification is the process by which an abstract idea about a computer program is turned into an explicit data model or other object created in a programming language. A computable/addressable object — a resource — is created in a system as a proxy for a non computable/addressable object...

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

See also

  • Duck typing
    Duck typing
    In computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface...

  • Inheritance (computer science)
    Inheritance (computer science)
    In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...

  • Polymorphism
    Polymorphism
    Polymorphism or dimorphism may refer to:-Biology:* Polymorphism , including:** having multiple phenotypes within a population; the switch that determines which phenotype an individual displays can be genetic or environmental...

  • Polymorphic association
    Polymorphic association
    Polymorphic association is a term used in discussions of Object-Relational Mapping with respect to the problem of representing in the relational database domain, a relationship from one class to multiple classes. In statically typed languages such as Java these multiple classes are subclasses of...

  • Virtual function
    Virtual function
    In object-oriented programming, a virtual function or virtual method is a function or method whose behaviour can be overridden within an inheriting class by a function with the same signature...


External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK