The Daily Parker

Politics, Weather, Photography, and the Dog

P is for Polymorphism

Blogging A to ZWe're now past the half-way point, 16 days into the Blogging A-to-Z challenge. Time to go back to object-oriented design fundamentals.

OO design has four basic concepts:

All four have specific meanings. Today we'll just look at polymorphism (from Greek: "poly" meaning many and "morph" meaning shape).

Essentially, polymorphism means using the same identifiers in different ways. Let's take a contrived but common example: animals.

Imagine you have a class representing any animal (see under "abstraction"). Animals can move. So:

public abstract class Animal
{
	public abstract void Move();
}

Notice that the Move method has no implementation, since animal species have many different ways of moving.

Now imagine two concrete animal classes:

public class Dog : Animal
{
	public override void Move() 
	{
		// Walk like a quadraped
	}
}

public class Guppy : Animal
{
	public override void Move() 
	{
		// Swim like a fish
	}
}

Guppies and dogs both move around just fine in their own environments, and dogs can move around in the littoral areas of a guppy's environment as well. So both animals have a Move method.

In this way, the Move method is polymorphic. A caller doesn't need to know anything about guppies or dogs in order to get them to move. And the implementations of the Move method will be completely different:

public void MoveAll(IEnumerable<Animal> animals)
{
	animals.ForEach(a => a.Move());
}

That method doesn't care what the list contains. It moves them all the same.

Now imagine this class:

public class Electron : Lepton
{
	public override void Move() 
	{
		// Walk like a quadraped
	}
}

Electrons move too. The implementation of Electron.Move() differs from Dog.Move() or Guppy.Move() so vastly that no one really knows how electrons do it. But if you call Electron.Move(), you expect the thing to move.

I've only given examples of subtyping and duck typing today, so it's worth reading more about polymorphism in general. Also, as you recall from my discussion of interfaces, you probably would also define an interface like IMovable to express that your class can move, rather than relying on the abstract classes and inheritance. (Program to interfaces, not to implementations!)

Comments are closed