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.

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.


CC BY-SA 4.0 Original Post