I was watching a googletechtalks video and they frequently refered to polymorphism what is it, what is it for, and how it it used?
Polymorphism is an important concept in object oriented programming which allows the programmers to know just what they must know. It is the perfect example of "sometimes less is more!"
EDIT:
Not sure why it is attracting down-votes but as far as I see; polymorphism, interfaces, delegates are all techniques of decoupling yourself from things you don't need to know. Oh yes, the word is "abstraction"...
Usually this refers the the ability for an object of type A to behave like an object of type B. In object oriented programming this is usually achieve by inheritance. Some wikipedia links to read more:
EDIT: fixed broken links.
Assuming OOP
http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming
General Type Polymorphism
http://en.wikipedia.org/wiki/Type_polymorphism
Most OOP books include sections on this.
Polymorphism is the ability to treat a class of object as if it is the parent class.
For instance, suppose there is a class called Animal, and a class called Dog that inherits from Animal. Polymorphism is the ability to treat any Dog object as an Animal object like so:
Dog* dog = new Dog;
Animal* animal = dog;
Let's use an analogy. For a given musical script every musician which plays it gives her own touch in the interpretation.
Musician can be abstracted with interfaces, genre to which musician belongs can be an abstrac class which defines some global rules of interpretation and every musician who plays can be modeled with a concrete class.
If you are a listener of the musical work, you have a reference to the script e.g. Bach's 'Fuga and Tocata' and every musician who performs it does it polymorphicaly in her own way.
This is just an example of a possible design (in Java):
public interface Musician {
public void play(Work work);
}
public interface Work {
public String getScript();
}
public class FugaAndToccata implements Work {
public String getScript() {
return Bach.getFugaAndToccataScript();
}
}
public class AnnHalloway implements Musician {
public void play(Work work) {
// plays in her own style, strict, disciplined
String script = work.getScript()
}
}
public class VictorBorga implements Musician {
public void play(Work work) {
// goofing while playing with superb style
String script = work.getScript()
}
}
public class Listener {
public void main(String[] args) {
Musician musician;
if (args!=null && args.length > 0 && args[0].equals("C")) {
musician = new AnnHalloway();
} else {
musician = new TerryGilliam();
}
musician.play(new FugaAndToccata());
}
In Object Oriented languages, polymorphism allows treatment and handling of different data types through the same interface. For example, consider inheritance in C++: Class B is derived from Class A. A pointer of type A* (pointer to class A) may be used to handle both an object of class A AND an object of class B.
I think this is an extremely valueable questions all though not in the way you intended. ;)
If you think about the (Latin, I think) roots of the term, it should become obvious.
- Poly = many (polygon = many-sided, polystyrene = many styrenes :-)
- Morph = change or form.
So polymorphism is the ability (in programming) to present the same interface for differing underlying forms (data types).
For example, integers and floats are implicitly polymorphic since you can add, subtract, multiply and so on, irrespective of the fact that the types are different. They're rarely considered as objects in the usual term.
But, in that same way, a class like BigDecimal
or Rational
or Imaginary
can also provide those operations, even though they operate on different data types.
The classic example is the Shape
class and all the classes that can inherit from it (square, circle, dodecahedron, irregular polygon and so on).
With polymorphism, each of these classes will have different underlying data. A point shape needs only two co-ordinates. A circle needs a center and radius. A square or rectangle needs two co-ordinates for the top left and bottom right corners (and possibly) a rotation.
And, by making the class responsible for its code as well as its data, you can achieve polymorphism. In this example, every class would have its own Draw()
function and the client code could simply do:
shape.Draw()
to get the correct behavior for any shape.
This is in contrast to the old way of doing things in which the code was separate from the data, and you would have had functions such as drawSquare()
and drawCircle()
.
Object orientation, polymorphism and inheritance are all closely-related concepts and they're vital to know. There have been many "silver bullets" during my long career which basically just fizzled out but the OO paradigm has turned out to be a good one. Learn it, understand it, love it - you'll be glad you did :-)
The term polymorphism comes from:
poly = many
morphism = the ability to change
In programming, polymorphism is a "technique" that lets you "look" at an object as being more than one type of thing. For instance:
A student object is also a person object. If you "look" (ie cast) at the student, you can probably ask for the student ID. You can't always do that with a person, right? (a person is not necessarily a student, thus might not have a student ID). However, a person probably has a name. A student does too.
Bottom line, "looking" at the same object from different "angles" can give you different "perspectives" (ie different properties or methods)
So this technique lets you build stuff that can be "looked" at from different angles.
Why do we use polymorphism? For starters ... abstraction. At this point it should be enough info :)
Generally speaking, it's the ability to interface a number of different types of object using the same or a superficially similar API. There are various forms:
Function overloading: defining multiple functions with the same name and different parameter types, such as sqrt(float), sqrt(double) and sqrt(complex). In most languages that allow this, the compiler will automatically select the correct one for the type of argument being passed into it, thus this is compile-time polymorphism.
Virtual methods in OOP: a method of a class can have various implementations tailored to the specifics of its subclasses; each of these is said to override the implementation given in the base class. Given an object that may be of the base class or any of its subclasses, the correct implementation is selected on the fly, thus this is run-time polymorphism.
Templates: a feature of some OO languages whereby a function, class, etc. can be parameterised by a type. For example, you can define a generic "list" template class, and then instantiate it as "list of integers", "list of strings", maybe even "list of lists of strings" or the like. Generally, you write the code once for a data structure of arbitrary element type, and the compiler generates versions of it for the various element types.
Polymorphism is the ability of the programmer to write methods of the same name that do different things for different types of objects, depending on the needs of those objects. For example, if you were developing a class called Fraction
and a class called ComplexNumber
, both of these might include a method called display()
, but each of them would implement that method differently. In PHP, for example, you might implement it like this:
// Class definitions
class Fraction
{
public $numerator;
public $denominator;
public function __construct($n, $d)
{
// In real life, you'd do some type checking, making sure $d != 0, etc.
$this->numerator = $n;
$this->denominator = $d;
}
public function display()
{
echo $this->numerator . '/' . $this->denominator;
}
}
class ComplexNumber
{
public $real;
public $imaginary;
public function __construct($a, $b)
{
$this->real = $a;
$this->imaginary = $b;
}
public function display()
{
echo $this->real . '+' . $this->imaginary . 'i';
}
}
// Main program
$fraction = new Fraction(1, 2);
$complex = new ComplexNumber(1, 2);
echo 'This is a fraction: '
$fraction->display();
echo "\n";
echo 'This is a complex number: '
$complex->display();
echo "\n";
Outputs:
This is a fraction: 1/2
This is a complex number: 1 + 2i
Some of the other answers seem to imply that polymorphism is used only in conjunction with inheritance; for example, maybe Fraction
and ComplexNumber
both implement an abstract class called Number
that has a method display()
, which Fraction and ComplexNumber are then both obligated to implement. But you don't need inheritance to take advantage of polymorphism.
At least in dynamically-typed languages like PHP (I don't know about C++ or Java), polymorphism allows the developer to call a method without necessarily knowing the type of object ahead of time, and trusting that the correct implementation of the method will be called. For example, say the user chooses the type of Number
created:
$userNumberChoice = $_GET['userNumberChoice'];
switch ($userNumberChoice) {
case 'fraction':
$userNumber = new Fraction(1, 2);
break;
case 'complex':
$userNumber = new ComplexNumber(1, 2);
break;
}
echo "The user's number is: ";
$userNumber->display();
echo "\n";
In this case, the appropriate display()
method will be called, even though the developer can't know ahead of time whether the user will choose a fraction or a complex number.
Polymorphism is this:
class Cup {
int capacity
}
class TeaCup : Cup {
string flavour
}
class CoffeeCup : Cup {
string brand
}
Cup c = new CoffeeCup();
public int measure(Cup c) {
return c.capacity
}
you can pass just a Cup instead of a specific instance. This aids in generality because you don't have to provide a specific measure() instance per each cup type
Polymorphism in coding terms is when your object can exist as multiple types through inheritance etc. If you create a class named "Shape" which defines the number of sides your object has then you can then create a new class which inherits it such as "Square". When you subsequently make an instance of "Square" you can then cast it back and forward from "Shape" to "Square" as required.
Polymorphism is when you can treat an object as a generic version of something, but you access it, the code determines which exact type it is and calls the associated code.
Here is an example in C#. Create four classes within a console application:
public abstract class Vehicle
{
public abstract int Wheels;
}
public class Bicycle : Vehicle
{
public override int Wheels()
{
return 2;
}
}
public class Car : Vehicle
{
public override int Wheels()
{
return 4;
}
}
public class Truck : Vehicle
{
public override int Wheels()
{
return 18;
}
}
Now create the following in the Main() of the module for the console application:
public void Main()
{
System.Collections.Generic.List<Vehicle> vehicles = new System.Collections.Generic.List<Vehicle>();
vehicles.Add(new Bicycle());
vehicles.Add(new Car());
vehicles.Add(new Truck());
foreach (Vehicle v in vehicles)
{
Console.WriteLine(string.Format("A {0} has {1} wheels.", v.GetType().Name, v.Wheels));
}
}
In this example, we create a list of the base class Vehicle, which does not know about how many wheels each of its sub-classes has, but does know that each sub-class is responsible for knowing how many wheels it has.
We then add a Bicycle, Car and Truck to the list.
Next, we can loop through each Vehicle in the list, and treat them all identically, however when we access each Vehicles 'Wheels' property, the Vehicle class delegates the execution of that code to the relevant sub-class.
This code is said to be polymorphic, as the exact code which is executed is determioned by the sub-class being referenced at runtime.
I hope that this helps you.