Polymorphism in Object-Oriented Programming
In Greek, "poly" means "many". For example, polygon means a many sided shape. Also in Greek, "morph" means "form". Morphology is the study of how words are "formed". Thus, polymorphism means "many forms".
In Computer Science, and particularly in Object-Oriented Programming, polymorphism refers to presenting the same interface for differing underlying forms (data types).
Polymorphism with Shapes
An example of Polymorphism is a Shape
class and all the classes that can inherit from this Shape class - classes like Point
, Square
, Circle
, Rectangle
, etc.
Polymorphism allows each of these classes to have different underlying data even though they inherit from the Shape class. A Point
shape only needs two co-ordinates as data. A Circle
shape needs a center and radius as data. Square
and Rectangle
shapes need four co-ordinates as data for the corners. Each of these shape classes will have different functionality while sharing a common interface.
Each class would have its own draw()
function that can be invoked on a shape object by doing circle.draw()
or rectangle.draw()
to get the right draw behavior for each type of shape.
polymorphism makes applications more modular. It saves us from having to create functions like drawRectangle()
and drawCircle()
all in one class. It also saves us from having many conditional statements in one draw()
function describing different behaviors per shape.
Polymorphism with Vehicles
Another example is that of a Vehicle
class with a wheels
property. A Bicycle
class can inherit from the Vehicle
class and override wheels
to be 2. A Car
class can inherit from the Vehicle
class and override wheels
to be 4. Each subclass is responsible for knowing how many wheels it has. The base class Vehicle
does not know about how many wheels its sub-classes have.
The Car
and Bicycle
classes are both of type Vehicle
, which means that we can add objects of both to an array/list of type Vehicle
. Then, we can loop over this array/list and treat each object the same way by referencing it's wheels
property. When we do reference each vehicle's wheels
property, the Vehicle
class will delegate that reference to it's corresponding sub-class.
The code that will be executed will be determined by the actual sub-class of the object being referenced at runtime, whether it's a Car
or a Bicycle
object.