What Is Polymorphism?

What Is Polymorphism?

 

Today we’ll tackle the last of the ‘traditional’ Object-Oriented Programming (OOP) concepts – Polymorphism. We have already explored EncapsulationAbstraction and Inheritance.

The term ‘polymorphism’ originates from Greek and means “many shapes”. Why many shapes? In OOP, this refers to the ability of an object to take on different forms. Different forms?

OK, let’s look at an example.

  private int CalcCircumferenceSum(params Shape[] shapes)
  {
     var sum = 0;
     foreach (var shape in shapes)
        sum += shape.Circumference;
     return sum; 
  }

The preceding function will calculate the aggregate circumference of a collection of Shape instances.

Here is the definition of Shape:

  public abstract class Shape
  {
     public abstract int Circumference { get; }
  }

Notice Shape is an abstract class. We cannot instantiate a Shape object, not directly. What we can do is create instances of concrete classes derived from Shape: Square, Rectangle, Triangle:

  public class Square : Shape
  {
     public int Side { get; private set; }

     public Square(int side)
     {
        Side = side;
     }

     public override int Circumference => 4 * Side;
  }

  public class Rectangle : Shape
  {
     public int Width { get; private set; } 
     public int Height { get; private set; } 

     public Rectangle (int width, int height)
     {
        Width = width;
        Height = height;
     }

     public override int Circumference => 2 * Width + 2 * Height;
  }

  public class Triangle : Shape
  {
     public int Side1 { get; private set; } 
     public int Side2 { get; private set; } 
     public int Side3 { get; private set; } 

     public Triangle (int side1, int side2, int side3)
     {
        Side1 = side1;
        Side2 = side2;
        Side3 = side3;
     }

     public override int Circumference => Side1 + Side2 + Side3;
  }

These are all Shapes, and as such, may be passed into our original Shape-accepting method, CalcCircumferenceSum():

  Shape square = new Square(7);
  Rectangle rectangle = new Rectangle(2, 4);
  var triangle = new Triangle(3, 6, 5);

  var sum = CalcCircumferenceSum(square, rectangle, triangle);

CalcCircumferenceSum() will call the correct Circumference property on the particular type of Shape, be it Square, Rectangle or Triangle.

Any reference to the base class, here Shape, may hold any one of the many concrete classes. The base class reference is polymorphic

Polymorphism is a much more powerful concept than merely being able to reference subclasses via their base class. We’ll explore a deeper, more significant type of polymorphism tomorrow.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply