Please see my other Web Development articles.
Leveraging the power of Object-Oriented Programming with Polymorphism
Related to inheritance, polymorphism illustrates a powerful advantage OOP over procedural programming.
It allows classes created to standardize attributes and behaviors, or provide a consistent interface for objects to later use when instantiated.
The example below demonstrates a common scenario where there are different types of employees – supervisor and CEO. Since both types will take vacations, there is no need for each type to define that behavior in its interface for objects to use.
Leveraging the important OOP principle of code reuse, the behavior of taking a vacation will instead be defined within an employee class which each type inherits.
With my parent or superclass defined (Employee), I will now create templates (class) for each employee type to create objects from.
Now I’m ready to instantiate my employee objects and demonstrate polymorphism.
In this example, notice how I define two types of employee type objects, then call the same exact named method (TakeVacation), but don’t specify when calling the method which class’ method to use.
At runtime, the compiler decides based on the type of object which implementation to use – TakeVacation() from Supervisor or MiddleManager.