Polymorphism is a pretty big word, but it’s actually a simple concept to understand. Here’s how it’s officially defined.
Polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface.
That may seem a little bit confusing to most of you new programmers. Luckily, polymorphism is a light switch concept meaning once you understand it, you know it forever.
So, what is polymorphism?
Basically, let’s say we had an apple, banana, and orange class. They’re all different, but they all fall under the same category as fruit. So, it would make sense to create an interface named fruit and have all these classes implement it. That’s what polymorphism is. It’s a bunch of classes with different functionality and structure, but all use the same interface.
Why would you use polymorphism in the first place?
Well, let’s go back to our fruit example. Let’s say for a moment that our fruit class was not an interface, but a class instead. Let’s also say that the apple, banana, and orange class didn’t exist. If we wanted to create a new fruit, we would have to use the fruit class. The fruit class is a very broad class because there’s many kinds of fruit. Every fruit is different and they taste different, but they’re all categorized under fruit.
In order to eat an orange, you have to peel the orange and then eat it, while you can just go ahead and bite an apple. Because of this, you have to define conditional statements to check whether or not you have to peel the fruit to eat it. This makes one huge messy class that ‘s not very efficient. Instead of creating a class for a broad subject, you can create an interface for a bunch of different classes that run differently.
While the classes may run differently, they have some common characteristics. Back to our fruit example, all fruit have to be grown. That’s what they have in common. Other than that, they’re all different sizes and shapes and texture. A pineapple for example, has spikes surrounding it.
So, if we had one universal class, why would an apple need a spike method? It would be better to create an interface with classes that implement it than have one class for everything. This is the power of polymorphism.
Hopefully you got it. To sum it all up, polymorphism is what unifies a bunch of classes with one interface. To learn more about polymorphism, then go here