Let’s imagine two butterflies with totally different wing colors. Both are butterflies and have characteristics of butterflies, what differs is only the color of their wings. Bringing this scenario to programming, if you had to program each of those butterflies, how would you do? The concept of polymorphism in object oriented programming helps you answer that question.
Polymorphism concept allows you to make the transcription of a particular method inherited from a parent class or superclass. Using the scenario of butterflies, we will explain the concept.
First we have to create the butterfly class, according to the concept of inheritance.
echo ‘- Color Black and Orange’;
$speed -> $v;
The Butterfly class now has two methods: one that displays the butterfly wing color and another that is triggered when they flap their wings and increment or not the variable speed.
Now let’s create two classes that inherit the attributes of the Butterfly class, but each has distinct wing colors from the superclass.
class BlueButterfly extends Butterfly
echo ‘- Blue Wing’;
class BlackBlueButterfly extends Butterfly
echo ‘- Black and Blue Wing’;
Both classes will inherit the standard methods of the class Butterfly, but ColorWing () method has been rewritten, since each has different color wings. So when the BlueButterfly object and BlackBlueButterfly are instantiated and there is a call to the ColorWing () method, the information that will be displayed will be the one implemented in the subclass. If a third class was created and that only inherit the methods and attributes of the superclass, to instantiate it and call it by ColorWing () method, the information showing on the screen would be the one available on the superclass method. To better understand this scenario let’s see an example:
class NormalButterfly extends Butterfly
$b1 -> new BlueButterfly()
$b2 -> new BlackBlueButterfly()
$b3 -> new NormalButterfly()
$b1 -> ColorWing()
$b2 -> ColorWing ()
$b3 -> ColorWing ()
The information showing on screen would be:
– Blue Wing
– Black and Blue Wing
– Black and Orange Wing
Polymorphism concept helps reuse source code, allowing much of a single code can be reused. It also facilitates the implementation of possible peculiarities of each object having attributes and methods in common.
Check out more content on our blog!
Learn all about Scriptcase.
You might also like…