C# Tutorial - Polymorphism

posted Jun 28, 2011, 7:31 PM by magic stone
Polymorphism comes from the Greek words of poly and morphos. The literal translation means "many forms", which in essence is how we use polymorphism in programming.

The easiest way to think about polymorphism is to use an example. Suppose that we are creating a piece of software such as a drawing/image package. As we draw shapes, we want to keep a list of what we add, this way we can remove them using the undo function. So if we created a collection of shapes, we could put squares, pentagons, or any of the shapes into the collection and the behaviour that they respond to is the same for each object in the collection.

A shape has many forms. Shape is just the generic name for them.

Coding Polymorphism

To demonstrate this lets look at some simple shapes. The base class will obviously be named Shape:

abstract class Shape
{
  public Point _loc;
  public Size _sz;

  public virtual void Draw(Graphics g)
  {
  }
}

The abstract keyword enables you to create classes solely for the purpose of inheritance. An abstract class can not be used to create an object.

The virtual keyword is used to modify a method declaration, and allow it to be overridden in a derived class.

Now let's create a derived class named Square:

class Square : Shape
{
  public override void Draw(Graphics g)
  {
    Pen p = new Pen(Color.Black, 3);
    g.DrawRectangle(p, _loc.X, _loc.Y, _sz.Width, _sz.Height);
    p.Dispose();
  }
}

We override the Draw method in order to draw our square on the screen.

Similarly let's create a class named Pentagon:

class Pentagon : Shape
{
  public override void Draw(Graphics g)
  {
    Pen p = new Pen(Color.Black, 3);
    Point[] pts = new Point[6];
    float a = 0;
    for (int c = 0; c < 5; c++)
    {
      pts[c] = new Point(
        (int)(_loc.X + ((_sz.Width / 2) * Math.Cos(a)) 
           + _sz.Width/2),
        (int)(_loc.Y + ((_sz.Height / 2) * Math.Sin(a))) 
           + _sz.Height/2);
      a += (float)Math.PI * 2 / 5;
    }
    pts[5] = pts[0];

    g.DrawPolygon(p, pts);
    p.Dispose();
  }
}

So now we have our shapes, we could have a collection class to hold our shapes called ShapeCollection.

class ShapeCollection : CollectionBase
{
  public void Add(Shape s)
  {
    List.Add(s);
  }
}

So we give ourselves an instance on the class and add our shapes to it.

ShapeCollection Shapes = new ShapeCollection();

for (int i = 0; i < 10; i++)
{
  Shape s = null;

  if ((i % 2) == 0)
    s = new Square();
  else
    s = new Pentagon();

  s._loc = new Point(20 + (i * 20), 20 + (i * 20));
  s._sz = new Size(20, 20);
  Shapes.Add(s);
}

We can now get each shape to draw itself

foreach (Shape s in Shapes)
  s.Draw(e.Graphics);
Comments