What is polymorphism, what is it for, and how is it used?
If you think about the Greek roots of the term, it should become obvious:
So, polymorphism is the ability (in programming) to present the same "interface" for differing underlying forms (data types). Note that the word "interface" here refers to the way in which a class is used, not necessarily the specific interface concept found in some object-oriented languages.
For example, in many languages, integers and floats are implicitly polymorphic since you can add, subtract, multiply and so on, irrespective of the fact that the types are different: result = 3.1 + 7
.
But, in that same way, classes like BigDecimal
, Rational
, Imaginary
, or Matrix
, can also provide those operations, even though they may operate on vastly different underlying data types.
A classic example is a Shape2d
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:
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 behaviour 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 :-)
(a) I originally wrote that as a joke but it turned out to be correct and, therefore, not that funny. The monomer styrene happens to be made from carbon and hydrogen, C8H8
, and polystyrene is made from groups of that, (C8H8)n
.
Perhaps I should have stated that a polyp was many occurrences of the letter p
although, now that I've had to explain the joke, even that doesn't seem funny either.
Sometimes, you should just quit while you're behind :-)