Information about Polymorphism In Object Oriented Programming
In simple terms, polymorphism lets you treat derived class members just like their parent class's members.
More precisely, polymorphism (object-oriented programming theory) is the ability of objects belonging to different types to respond to method 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, so this behavior can be implemented at run time (this is called late binding or dynamic binding).
The different objects involved only need to present a compatible interface to the clients (the calling routines). That is, there must be public methods with the same name and the same parameter sets in all the objects. In principle, the object types may be unrelated, but since they share a common interface, they are often implemented as subclasses of the same parent class. 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).
In practical terms, polymorphism means that if class B inherits from class A, it doesn’t have to inherit everything about class A; it can do some of the things that class A does differently. This means that the same “verb” can result in different actions as appropriate for a specific class, so controlling code can issue the same command to a series of objects and get appropriately different results from each one.
Overloading Polymorphism is the use of one method signature, or one operator such as "+", to perform several different functions depending on the implementation. The "+" operator, for example, may be used to perform integer addition, float addition, list concatenation, or string concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add together properly in an OOP language. The language must therefore overload the concatenation operator, "+", to work this way. This helps improve code readability.
(In C++, for instance, this is possible because the interface definition for a class defines a memory layout, the virtual function table describing where pointers to functions can be found. Future, new classes can work with old, precompiled code because the new classes must conform to the abstract class interface, meaning that the layout of the new class's virtual function table is the same as before; the old, precompiled code can still look at the same memory offsets relative to the start of the object's memory in order to find a pointer to the new function. It is only that the new virtual function table points to a new implementation of the functions in the table, thus allowing new, interface-compliant behavior with old, precompiled code.)
Since program evolution very often appears in the form of adding types of objects (i.e. classes), this ability to cope with and localize change that polymorphism allows is the key new contribution of object technology to software design.
However, the most common examples of polymorphism are found in custom classes. Consider the example below, where two subclasses (Cat and Dog) are derived from an Animal superclass. Two Cat objects and one Dog are instantiated and given names, and then they are gathered in a list ([a, b, c]) and their talk method is called.
Note that Python makes polymorphism particularly easy to write, since the language is dynamically (and implicitly) typed: a name can be bound to objects of any type (or class) without having to explicitly specify the type, and a list holds mixed type (unlike a C array or a Java array, be it generic or not). Note the inevitable trade-off though: a language that generates fewer compile-time errors tends to generate more run-time errors, requiring explicit (unit) testing.
Consider the equivalent program in C++:
Note that the
Consider the equivalent program in Visual Basic .NET. One way of doing polymorphism is through the definition and implementation of a common interface. Consider the example below, where two subclasses (Cat and Dog) implement the IAnimal interface. Two Cat objects and one Dog are instantiated and given names, and then they are gathered in a list and their talk method is called.
class Shape { void draw() { }
void erase() { } }
class Circle extends Shape { void draw() { System.out.println("Circle.draw()"); }
void erase() { System.out.println("Circle.erase()"); } }
class Square extends Shape { void draw() { System.out.println("Square.draw()"); }
void erase() { System.out.println("Square.erase()"); } }
class Triangle extends Shape { void draw() { System.out.println("Triangle.draw()"); }
void erase() { System.out.println("Triangle.erase()"); } }
// A "factory" that randomly creates shapes:
class RandomShapeGenerator { private Random rand = new Random();
public Shape next() { switch (rand.nextInt(3)) { default: case 0: return new Circle(); case 1: return new Square(); case 2: return new Triangle(); } } }
public class ShapesDemo { private static RandomShapeGenerator gen = new RandomShapeGenerator();
public static void main(String[] args) { Shape[] s = new Shape[9]; // Fill up the array with shapes: for (int i = 0; i < s.length; i++) s[i] = gen.next(); // Make polymorphic method calls: for (int i = 0; i < s.length; i++) s[i].draw();
} }
Consider it in Xbase++
More precisely, polymorphism (object-oriented programming theory) is the ability of objects belonging to different types to respond to method 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, so this behavior can be implemented at run time (this is called late binding or dynamic binding).
The different objects involved only need to present a compatible interface to the clients (the calling routines). That is, there must be public methods with the same name and the same parameter sets in all the objects. In principle, the object types may be unrelated, but since they share a common interface, they are often implemented as subclasses of the same parent class. 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).
In practical terms, polymorphism means that if class B inherits from class A, it doesn’t have to inherit everything about class A; it can do some of the things that class A does differently. This means that the same “verb” can result in different actions as appropriate for a specific class, so controlling code can issue the same command to a series of objects and get appropriately different results from each one.
Overriding and Overloading
If a Dog is commanded to speak(), this may emit a Bark. However, if a Pig is commanded to speak(), this may emit an Oink. They both inherit speak() from Animal, but their derived class methods override the methods of the parent class; this is Overriding Polymorphism.Overloading Polymorphism is the use of one method signature, or one operator such as "+", to perform several different functions depending on the implementation. The "+" operator, for example, may be used to perform integer addition, float addition, list concatenation, or string concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add together properly in an OOP language. The language must therefore overload the concatenation operator, "+", to work this way. This helps improve code readability.
Advantages of polymorphism
Polymorphism allows client programs to be written based only on the abstract interfaces of the objects which will be manipulated (interface inheritance). This means that future extension in the form of new types of objects is easy, if the new objects conform to the original interface. In particular, with object-oriented polymorphism, the original client program does not even need to be recompiled (only relinked) in order to make use of new types exhibiting new (but interface-conformant) behavior.(In C++, for instance, this is possible because the interface definition for a class defines a memory layout, the virtual function table describing where pointers to functions can be found. Future, new classes can work with old, precompiled code because the new classes must conform to the abstract class interface, meaning that the layout of the new class's virtual function table is the same as before; the old, precompiled code can still look at the same memory offsets relative to the start of the object's memory in order to find a pointer to the new function. It is only that the new virtual function table points to a new implementation of the functions in the table, thus allowing new, interface-compliant behavior with old, precompiled code.)
Since program evolution very often appears in the form of adding types of objects (i.e. classes), this ability to cope with and localize change that polymorphism allows is the key new contribution of object technology to software design.
Examples
Python makes extensive use of polymorphism in its basic types. For example, strings (immutable sequences of characters) and lists (mutable sequences of elements of any type) have the same indexing interface and the same lookup interface (which call the appropriate underlying methods).> myString = 'Hello world' myList = [0, 'one', 1, 'two', 3, 'five', 8] print myString[:5] # prints Hello print myList[:5] # prints [0, 'one', 1, 'two', 3] print 'e' in myString # prints True print 5 in myList # prints False
However, the most common examples of polymorphism are found in custom classes. Consider the example below, where two subclasses (Cat and Dog) are derived from an Animal superclass. Two Cat objects and one Dog are instantiated and given names, and then they are gathered in a list ([a, b, c]) and their talk method is called.
>
class Animal:
def __init__(self, name):
self.name = name
class Cat(Animal):
def talk(self):
return 'Meow!'
class Dog(Animal):
def talk(self):
return 'Arf! Arf!'
a = Cat('Missy')
b = Cat('Mr. Bojangles')
c = Dog('Lassie')
for animal in [a, b, c]:
print animal.name + ': ' + animal.talk()
# prints the following:
#
# Missy: Meow!
# Mr. Bojangles: Meow!
# Lassie: Arf! Arf!
Note that Python makes polymorphism particularly easy to write, since the language is dynamically (and implicitly) typed: a name can be bound to objects of any type (or class) without having to explicitly specify the type, and a list holds mixed type (unlike a C array or a Java array, be it generic or not). Note the inevitable trade-off though: a language that generates fewer compile-time errors tends to generate more run-time errors, requiring explicit (unit) testing.
Consider the equivalent program in C++:
> #include#include #include using namespace std; class Animal { public: Animal(const string & name) : name(name) { } virtual ~Animal() { } virtual const string talk() = 0; const string name; }; class Cat : public Animal { public: Cat(const string & name) : Animal(name) { } virtual ~Cat() { } virtual const string talk() { return "Meow!"; } }; class Dog : public Animal { public: Dog(const string & name) : Animal(name) { } virtual ~Dog() { } virtual const string talk() { return "Arf! Arf!"; } }; // prints the following: // // Missy: Meow! // Mr. Bojangles: Meow! // Lassie: Arf! Arf! // int main() { Animal *animals [] = { new Cat("Missy"), new Cat("Mr. Bojangles"), new Dog("Lassie") }; for (int i = 0; i < 3; ++i) cout << animals[i]->name << ": " << animals[i]->talk() << endl; for (int i = 0; i < 3; ++i) delete animals[i]; return 0; }
Note that the
talk() method is explicitly declared as virtual. This is because polymorphic method calls have relatively high overhead in C++ [1]. This overhead is lessened by treating all method calls as non-polymorphic, unless explicitly marked as virtual by the developer.
Consider the equivalent program in Visual Basic .NET. One way of doing polymorphism is through the definition and implementation of a common interface. Consider the example below, where two subclasses (Cat and Dog) implement the IAnimal interface. Two Cat objects and one Dog are instantiated and given names, and then they are gathered in a list and their talk method is called.
>
Namespace std
Public Interface IAnimal
ReadOnly Property Name() As String
Function Talk() As String
End Interface
Public Class Cat
Implements IAnimal
Private mName As String
Sub New(ByVal name As String)
mName = name
End Sub
Public ReadOnly Property Name() As String Implements IAnimal.Name
Get
Return mName
End Get
End Property
Public Function Talk() As String Implements IAnimal.Talk
Return "Meow!"
End Function
End Class
Public Class Dog
Implements IAnimal
Private mName As String
Sub New(ByVal name As String)
mName = name
End Sub
Public ReadOnly Property Name() As String Implements IAnimal.Name
Get
Return mName
End Get
End Property
Public Function Talk() As String Implements IAnimal.Talk
Return "Arf! Arf!"
End Function
End Class
Public Module TestAnimals
' Prints the following:
'
' Missy: Meow!
' Mr. Bojangles: Meow!
' Lassie: Arf! Arf!
Public Sub Main()
Dim animals(3) As IAnimal
animals(0) = New Cat("Missy")
animals(1) = New Cat("Mr. Bojangles")
animals(2) = New Dog("Lassie")
For i As Integer = 0 To 2
Console.Out.WriteLine("{0}: {1}", animals(i).Name, animals(i).Talk)
Next
End Sub
End Module
End Namespace
Consider it in Java:
import java.util.Random;class Shape { void draw() { }
void erase() { } }
class Circle extends Shape { void draw() { System.out.println("Circle.draw()"); }
void erase() { System.out.println("Circle.erase()"); } }
class Square extends Shape { void draw() { System.out.println("Square.draw()"); }
void erase() { System.out.println("Square.erase()"); } }
class Triangle extends Shape { void draw() { System.out.println("Triangle.draw()"); }
void erase() { System.out.println("Triangle.erase()"); } }
// A "factory" that randomly creates shapes:
class RandomShapeGenerator { private Random rand = new Random();
public Shape next() { switch (rand.nextInt(3)) { default: case 0: return new Circle(); case 1: return new Square(); case 2: return new Triangle(); } } }
public class ShapesDemo { private static RandomShapeGenerator gen = new RandomShapeGenerator();
public static void main(String[] args) { Shape[] s = new Shape[9]; // Fill up the array with shapes: for (int i = 0; i < s.length; i++) s[i] = gen.next(); // Make polymorphic method calls: for (int i = 0; i < s.length; i++) s[i].draw();
} }
Consider it in Xbase++
>
#include "class.ch"
//
// This program prints:
//
// Missy Meow!
// Mr. Bojangles Meow!
// Lassie Barf!
// Press any key to continue...
//
/////////////////////////////
//
PROCEDURE Main()
//
/////////////////////////////
LOCAL aAnimals := Array(3)
LOCAL i
aAnimals[1] := Cat():New("Missy")
aAnimals[2] := Cat():New("Mr. Bojangles")
aAnimals[3] := Dog():New("Lassie")
FOR i:=1 TO LEN(aAnimals)
? aAnimals[i]:Name + " " + aAnimals[i]:Talk()
NEXT i
WAIT
RETURN
/////////////////////////////
//
CLASS Animal
//
/////////////////////////////
EXPORTED:
VAR Name READONLY
METHOD Init
DEFERRED CLASS METHOD Talk
ENDCLASS
METHOD Animal:Init( cName )
::Name := cName
RETURN Self
/////////////////////////////
//
CLASS Dog FROM Animal
//
/////////////////////////////
EXPORTED:
METHOD Talk
ENDCLASS
METHOD Dog:Talk()
RETURN "Barf!"
/////////////////////////////
//
CLASS Cat FROM Animal
//
/////////////////////////////
EXPORTED:
METHOD Talk
ENDCLASS
METHOD Cat:Talk()
RETURN "Meow!"
Other concepts
In non-object-oriented programming languages, the term polymorphism has different, but related meanings; one of these, parametric polymorphism, is known as generic programming in the OOP community and is supported by many languages including C++, Eiffel, and recent versions of C# and Java.References
1. ^ Driesen, Karel and Hölzle, Urs, "The Direct Cost of Virtual Function Calls in C++", OOPSLA 1996
External links
Object-oriented programming (OOP) is a programming paradigm that uses "objects" and their interactions to design applications and computer programs. It is based on several techniques, including inheritance, modularity, polymorphism, and encapsulation.
..... Click the link for more information.
..... Click the link for more information.
In the programming paradigm of object-oriented programming, an object is the individual run-time unit that is used as the basic building block of programs. These objects act on each other, as opposed to a traditional view in which a program may be seen as a collection of functions,
..... Click the link for more information.
..... Click the link for more information.
In programming languages a data type defines a set of values and the allowable operations on those values[1]. For example, in the Java programming language, the "int" type represents the set of 32-bit integers ranging in value from -2,147,483,648 to 2,147,483,647, and
..... Click the link for more information.
..... Click the link for more information.
confusing or unclear for some readers.
Please help [ improve the article] or discuss these issues on the talk page. In object-oriented programming, the term method refers to a subroutine that is exclusively associated either with a class (called class methods
..... Click the link for more information.
Please help [ improve the article] or discuss these issues on the talk page. In object-oriented programming, the term method refers to a subroutine that is exclusively associated either with a class (called class methods
..... Click the link for more information.
Dynamic binding is the practice of figuring out which method to invoke at runtime. For example, if we write
void kill(Mortal m)
it's not clear whether m is a Person or a Plant, and thus whether Plant.die() or Person.die() should be invoked on the object.
..... Click the link for more information.
void kill(Mortal m)
it's not clear whether m is a Person or a Plant, and thus whether Plant.die() or Person.die() should be invoked on the object.
..... Click the link for more information.
An interface defines the communication boundary between two entities, such as a piece of software, a hardware device, or a user. It generally refers to an abstraction that an entity provides of itself to the outside.
..... Click the link for more information.
..... Click the link for more information.
In computer science, a subroutine (function, method, procedure, or subprogram) is a portion of code within a larger program, which performs a specific task and can be relatively independent of the remaining code.
..... Click the link for more information.
..... Click the link for more information.
In computer programming, a parameter is a variable which takes on the meaning of a corresponding argument passed in a call to a subroutine. In the most common case, call-by-value, a parameter acts within the subroutine as a local (isolated) copy of the argument, but in other
..... Click the link for more information.
..... Click the link for more information.
In object-oriented programming, a subclass is a class that inherits some properties from its superclass.
You can usually think of the subclass as being "a kind of" its superclass, as in a "a Manx is a kind of cat", or "a square is a kind of rectangle":
..... Click the link for more information.
You can usually think of the subclass as being "a kind of" its superclass, as in a "a Manx is a kind of cat", or "a square is a kind of rectangle":
- A cat
..... Click the link for more information.
In computer science, a superclass is a class from which other classes are derived. A superclass is also called a parent class. The classes that are derived from a superclass are known as child classes, derived classes, or subclasses.
..... Click the link for more information.
..... Click the link for more information.
In computer science, abstraction is a mechanism and practice to reduce and factor out details so that one can focus on a few concepts at a time.
The following English definition of abstraction helps to understand how this term applies to Computer Science, IT and Objects - i.
..... Click the link for more information.
The following English definition of abstraction helps to understand how this term applies to Computer Science, IT and Objects - i.
..... Click the link for more information.
In object-oriented programming, interface inheritance is type of inheritance wherein one or more classes share a set of messages. This sharing can be realized by agreement, as in Python, or by use of programming-language-specific machinery, as in Java.
..... Click the link for more information.
..... Click the link for more information.
compiler is a computer program (or set of programs) that translates text written in a computer language (the source language) into another computer language (the target language).
..... Click the link for more information.
..... Click the link for more information.
linker or link editor is a program that takes one or more objects generated by compilers and assembles them into a single executable program.
In IBM mainframe environments such as OS/360 this program is known as a linkage editor.
..... Click the link for more information.
In IBM mainframe environments such as OS/360 this program is known as a linkage editor.
..... Click the link for more information.
A virtual method table, virtual function table, dispatch table, or vtable, is a mechanism used in programming language implementations in order to support dynamic polymorphism, i.e., run-time method binding.
..... Click the link for more information.
..... Click the link for more information.
Python
Paradigm: Multi-paradigm
Appeared in: 1991
Designed by: Guido van Rossum
Developer: Python Software Foundation
Latest release: 2.5.1/ April 18 2007
Latest unstable release: 3.
..... Click the link for more information.
Paradigm: Multi-paradigm
Appeared in: 1991
Designed by: Guido van Rossum
Developer: Python Software Foundation
Latest release: 2.5.1/ April 18 2007
Latest unstable release: 3.
..... Click the link for more information.
Immutability may refer to the following:
..... Click the link for more information.
- Immutable object, in computer science
- Immutability (theology), the belief that God cannot change
..... Click the link for more information.
In computer programming, unit testing is a procedure used to validate that individual units of source code are working properly. A unit is the smallest testable part of an application. In procedural programming a unit may be an individual program, function, procedure, etc.
..... Click the link for more information.
..... Click the link for more information.
This article or section may be confusing or unclear for some readers.
Please [improve the article] or discuss this issue on the talk page. This article has been tagged since April 2007.
..... Click the link for more information.
Please [improve the article] or discuss this issue on the talk page. This article has been tagged since April 2007.
..... Click the link for more information.
Generic programming is a style of computer programming where algorithms are written in an extended grammar and are made adaptable by specifying variable parts that are then somehow instantiated later by the compiler with respect to the base grammar.
..... Click the link for more information.
..... Click the link for more information.
C++
Paradigm: Multi-paradigm
Appeared in: 1983
Designed by: Bjarne Stroustrup
Typing discipline: Static, unsafe, nominative
Major implementations: G++, Microsoft Visual C++, Borland C++ Builder
Dialects: ISO/IEC C++ 1998, ISO/IEC C++ 2003
..... Click the link for more information.
Paradigm: Multi-paradigm
Appeared in: 1983
Designed by: Bjarne Stroustrup
Typing discipline: Static, unsafe, nominative
Major implementations: G++, Microsoft Visual C++, Borland C++ Builder
Dialects: ISO/IEC C++ 1998, ISO/IEC C++ 2003
..... Click the link for more information.
Eiffel
Paradigm: object-oriented
Appeared in: 1986
Designed by: Bertrand Meyer
Developer: Bertrand Meyer & Eiffel Software
Typing discipline: static typing, strong typing
Major implementations: EiffelStudio, SmartEiffel, Visual Eiffel
..... Click the link for more information.
Paradigm: object-oriented
Appeared in: 1986
Designed by: Bertrand Meyer
Developer: Bertrand Meyer & Eiffel Software
Typing discipline: static typing, strong typing
Major implementations: EiffelStudio, SmartEiffel, Visual Eiffel
..... Click the link for more information.
C#
Paradigm: structured, imperative, object-oriented
Appeared in: 2001 (last revised 2005)
Designed by: Microsoft Corporation
Typing discipline: static, strong, both safe and unsafe, nominative
Major implementations: .NET Framework, Mono, DotGNU
Dialects: 1.
..... Click the link for more information.
Paradigm: structured, imperative, object-oriented
Appeared in: 2001 (last revised 2005)
Designed by: Microsoft Corporation
Typing discipline: static, strong, both safe and unsafe, nominative
Major implementations: .NET Framework, Mono, DotGNU
Dialects: 1.
..... Click the link for more information.
Java
Paradigm: Object-oriented, structured, imperative
Appeared in: 1995
Designed by: Sun Microsystems
Typing discipline: Static, strong, safe, nominative
Major implementations: Numerous
Influenced by: Objective-C, C++, Smalltalk, Eiffel,[1]
..... Click the link for more information.
Paradigm: Object-oriented, structured, imperative
Appeared in: 1995
Designed by: Sun Microsystems
Typing discipline: Static, strong, safe, nominative
Major implementations: Numerous
Influenced by: Objective-C, C++, Smalltalk, Eiffel,[1]
..... Click the link for more information.
This article is copied from an article on Wikipedia.org - the free encyclopedia created and edited by online user community. The text was not checked or edited by anyone on our staff. Although the vast majority of the wikipedia encyclopedia articles provide accurate and timely information please do not assume the accuracy of any particular article. This article is distributed under the terms of GNU Free Documentation License.
Herod_Archelaus