Thursday, May 31, 2012

What is Polymorphism?

If you think about the Greek roots of the term, it should become obvious.
  • Poly = many: polygon = many-sided, polystyrene = many styrenes, polyglot = many languages, and so on.
  • Morph = change or form: morphology = study of biological form, Morpheus = the Greek god of dreams able to take any 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, splat and so on).
With polymorphism, each of these classes will have different underlying data. A point shape needs only two co-ordinates (assuming it's in a two-dimensional space of course). 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. An irregular polygon needs a series of lines.
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 :-)

http://stackoverflow.com/questions/1031273/what-is-polymorphism

2 comments:

  1. Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

    http://www.tutorialspoint.com/java/java_polymorphism.htm

    ReplyDelete
  2. In computer science the term polymorphism means “a
    method the same as another in spelling but with different behavior.” The computer differentiates between (or
    among) methods depending on either the method signature (after compile) or the object reference (at run time).

    http://apcentral.collegeboard.com/apc/public/repository/Intro_to_Polymorphismin_Umbargar.pdf

    ReplyDelete