Why is overload considered a form of polymorphism, or a way to achieve polymorphism.
Polymorphism for me mean multiple form and I don't quite see how overloading help achieving this.
Polymorphism is something that happens at runtime. In terms of OOP, it's the practice of calling a method, and, at compile time, not knowing which object the method will be called on. The classic example is with Shapes, Circles, Squares, etc. You have a collection of Shapes, each of which is instantiated to a Circle, Square, whatever. The compiler neither knows nor cares which type of Shape you're calling Draw or Erase on at any given time; that determination happens when the program is run.
Method overloading happens at compile time. You have multiple methods with the same name, but different parameters. When you call one of the methods, the compiler will decide which of the overloads best matches based on the parameters you supplied.
Why is overload considered a form of polymorphism, or a way to achieve polymorphism.
At root, polymorphism is the ability to treat multiple types under the same API. So technically, method overloading does fall under this. In fact, according to wikipedia, method overloading is known as "ad-hoc polymorphism", but I've never heard this term used in real life (not that I'm the final authority). Usually polymorphism refers exclusively to the dynamic binding of methods, as in the Shape, Circle, Square example.
There's also "parametric polymorphism", though that's usually, again by my perhaps limited experience, referred to as either generics or templates depending on the language (they are not the same; there are subtle differences between the two)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With