Polymorphism is one of those terms you hear in Computer Science that sounds confusing at first and overly complicated, until you find out you’ve probably been using it this whole time. “Polymorphism in Programming” by Johnathan Johnson is a great blog detailing exactly what it is and how it works. It gives a nice clear definition that’s easy to understand and then lists out the different types you’ll encounter along your programming journey.
Polymorphism is essentially just a process that can perform multiple tasks depending on the context of the situation. There are many forms of polymorphism as well such as Subtype (Runtime), Ad hoc (Compile-time), Parametric (Overloading), and Coercion (Casting). I won’t get too in-depth on each of these as Johnson has already done a great job of this in his blog.
The key takeaway here is that polymorphism allows you to program an interface, not just an implementation. What I mean is by creating an interface or superclass it doesn’t matter what type the object being called is you can just call the method on it. For example, you could have a list of Shape objects that can hold a circle or a square or whatever shape you want, and you can call draw() without caring which specific subclass you’re dealing with. Because of this code duplication can be severely cut down due to multiple objects using the same method all stored in the superclass.
This is similar to what we saw in class with the Duck superclass and all the subclasses with different duck types. As long as you were calling a method stored within the superclass it didn’t matter which subclass you were calling it on. Even if the subclass had overridden the method, you would just be running into ad hoc polymorphism as the program would be switching the version of the method used to that of the one stored in that particular subclass.
Even though I’ve been using polymorphism for years through my career here at Worcester State it’s good to finally learn what this practice is actually called. It’s also good to learn that there are forms of it I wasn’t always using when I could of and instead took the less efficient route to solve my problem. The concept is integral to time efficiency and when programming time is incredibly important in a lot of ways.
I plan on taking this newfound knowledge with me through the rest of my career here as well as whatever the future holds for me.
From the blog CS@Worcester – DPCS Blog by Daniel Parker and used with permission of the author. All other rights reserved by the author.