What is polymorphism in OOP?

Polymorphism in OOP Theory is the ability to:

  • Invoke an operation on an instance of a specialized type by only knowing its generalized type while calling the method of the specialized type and not that of the generalized type: this is dynamic polymorphism.
  • Define several methods having the save name but having differents parameters: this is static polymorphism.

The first if the historical definition and the most important.

It allows to create strongly-typed consistency of the class hierarchy and to do some magical things like managing lists of objects of differents types without knowing their types but only one of their parent type, as well as data bindings.

Here are some Shapes like Point, Line, Rectangle and Circle having the operation Draw() taking either nothing or either a parameter to set a timeout to erase it.

public class Shape
{
public virtual void Draw()
{
DoNothing();
}
public virtual void Draw(int timeout)
{
DoNothing();
}
}

public class Point : Shape
{
int X, Y;
public override void Draw()
{
DrawThePoint();
}
}

public class Line : Point
{
int Xend, Yend;
public override Draw()
{
DrawTheLine();
}
}

public class Rectangle : Line
{
public override Draw()
{
DrawTheRectangle();
}
}

var shapes = new List<Shape>
{
new Point(0,0),
new Line(0,0,10,10),
new rectangle(50,50,100,100)
};

foreach ( var shape in shapes )
shape.Draw();

Here the Shape class and the Shape.Draw() methods should be marked as abstract.

They are not for to make understand.

Without polymorphism, using abstract-virtual-override, while parsing the shapes, it is only the Spahe.Draw() method that is called as the CLR don't know what method to call. So it call the method of the type we act on, and here the type is Shape because of the list declaration. So the code do nothing at all.

With polymorphism, the CLR is able to infer the real type of the object we act on using what is called a virtual table. So it call the good method, and here calling Shape.Draw() if Shape is Point calls the Point.Draw(). So the code draws the shapes.

Links

CC BY-SA 4.0 Original Post