views:

828

answers:

15

I was watching a googletechtalks video and they frequently refered to polymorphism what is it, what is it for, and how it it used?

A: 

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

Hemant
I +1'd it, I have to say when I skimmed it first I thought "...know what they must know" was a smartaleck answer, and then I realised that it gets to the heart of why the issue is important. Sometimes less is more indeed.
d__
+5  A: 

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.

JesperE
"the ability for an object of type A to behave like an object of type B" - it's not accurate definition. I would say it's more like the ability to treat an object of type A like it's an object of type B.
Artem Barger
Yes. Maybe that is a better phrasing.
JesperE
For completeness, many language implement polymorphism through duck typing, e.g. Python.
ilya n.
+2  A: 

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.

Aiden Bell
That's not a real answer. Everyone is able to search for this terms. How about explaining them.
Ionuț G. Stan
@Ionut - I am sure a mature set of wikipedia articles can do the topic more justice and provide more information than I can in an SO answer. Don't you?
Aiden Bell
How about dropping SO because the Internet provides more information? Don't get me wrong, but there were much more easier/harder questions that got a lot of detailed answer and nobody said "go to Wikipedia".
Ionuț G. Stan
maybe those kind of answers should be wiki'd
Brann
Well my point half-was that there are tons of places to find this information in a better format than SO can provide. Don't like it? Post an answer yourself, as detailed as you like
Aiden Bell
+2  A: 

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;
Tom Dalling
+1  A: 

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());
}
Boris Pavlović
A: 

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.

Eran Rehavi
A: 

I think this is an extremely valueable questions all though not in the way you intended. ;)

AnthonyWJones
+4  A: 

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 :-)

paxdiablo
Greek, not Latin :) (the 'y' and 'ph' are the giveaways). And in the Greek, 'morph-' is *just* 'shape', or 'form' - the English meaning of '*change* shape' for 'morph' is a later development
AakashM
A: 

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 :)

tzup
A: 

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.

Stewart
+1  A: 

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.

Alex Basson
That's not polymorphism. That's two classes having methods of the same name. They would need to be linked by a base class or interface called "displayable" or something similiar, and then other methods would simply care that the object is of type "displayable" rather than Complex or Fraction.
Pod
I always thought polymorphism *was* "two classes having methods of the same nome." In fact, to quote Stephan Kochan (from whom I'm shameless ripping off this Fraction/Complex example), "the ability to share the same method name across different classes is known as polymorphism." (from _Programming_In_Objective-C_) He doesn't mention any need to link classes through a base class. Maybe it's different in different languages, I honestly don't know.
Alex Basson
Even tough this defenition is quoted from a published book, I would still argue that it is incorrect. Especially since it seems to clash with every other, language agnostic defenition of polymorphism. And while the final result is the same as seen with polymorphism, I would argue that it is instead the dynamic typing that allows programmer be able to thrust that the correct implementation of a method among other, similary named methods is being called.
DJ Pirtu
+1  A: 

This wikipedia article has good examples in many languages.

Tim Hoolihan
+3  A: 

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

Vinko Vrsalovic
A: 

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.

Brian Scott
+4  A: 

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.

Antony Gibbs