Polymorphism
Dictionary: “The condition of occurring in several different forms”
Wikipedia: “from the Greek roots "poly" (many) and "morphe" (form, shape, structure)” and “the ability in computer programming to present the same programming interface for differing underlying forms (data types, classes)”
There are two forms of polymorphism, run-time polymorphism (overriding) and compile time polymorphism (overloading).
Run time polymorphism - Overriding - class overrides a method in its parent. The decision as to which one to call is made at run time according to the object used. This is typically what people refer to when they talk about polymorphism. Onwards to an example:
We’ve got a class for a duck:
And a RubberDuck class, which is clearly a type of duck:
public class RubberDuck : Duck
{
public override void MakeNoise()
{
Squeek(); //rubber ducks don`t go quack
}
private void Squeek()
{
Console.Write("Squeek"); }
}
}
We’re then going to use those ducks:
Duck myDuck;
myDuck = new Duck();
myDuck.MakeNoise(); //Quacks
myDuck = new RubberDuck();
myDuck.MakeNoise(); //Squeeks
Here you can see that we’re calling the MakeNoise method and we get a different noise according to the object used. That’s runtime polymorphism!
Compile time polymorphism - Overloading - e.g. multiple overloads of a method with different signatures, at compile time you know which method is being called. I hadn’t realised this was referred to as polymorphism, to me it was just overloading – so there you go, every day is a school day! An example:
public class Stuff
{
public void DoStuff()
{
//do some stuff
}
public void DoStuff(string stuffToDo)
{
//Do some stuff but with a parameter
}
}
So this class does stuff, sorry - I’m running low on creativity! You can see it has two different methods called DoStuff, one has a parameter, one doesn’t. Then when we want to call DoStuff, we decide which one to call, so:
Stuff stuff = new Stuff();
stuff.DoStuff();
stuff.DoStuff("coolStuff");
We’re choosing which one to call according to what we want. That is compile time polymorphism!
Got a comment or correction (I’m not perfect) for this post? Please leave a comment below.
Subscribe to Gavin Johnson-Lynn
Get the latest posts delivered right to your inbox