OOP basics: Polymorphism Explained!
So; is polymorphism just “being able to perform functions of an interface, such as adding, subtracting, etc, on objects of different data types such as integers, floats, etc”?
Is it basically operator overloading?
Polymorphism: How to Make it Work
Suppose that instead of thinking of using polymorphism at a large scale, think of it at a much smaller scale. Don’t try to get some polymorphic sense about vehicle overall, but think about how vehicles are actually built in the real world.
I’ll take bicycle as a simple example.
The bike I’m thinking of is composed of parts. It has a seat, wheels, gears, etc. I’ll focus on just those. It is is suitable for trail riding and for expeditions and even for the road. When we first purchase; it the bike is set up primarily for moderately comfortable use on mild trails. It work well for that.
But the parts are all replaceable. By changing the saddle we can make it better fit my anatomy. By changing the wheels I can make it much nicer on the road — both lighter and with a smoother ride. And by changing the gears — even the number of gears we can make it more useful for serious rocky trails or for more modest prepared surfaces.
We can easily swap parts and by giving it one part at one time and a different part at another time we can give it different behaviour. It is the behaviour that is polymorphic, not the interface. The two sets of wheels we have for this bike are interchangeable, but behave very differently. The saddles enable one use or another, for one rider or another. But the interface between the saddle and the rest of the bike is fixed. And we don’t need to remember each time we switch gears whether we have the road wheels or the trail wheels on the bike. It “works” the same, but “behaves” differently without any decisions (if-this-then-that) on our part as we ride.
We can build software this way also. Build complex objects with composition — lots of part. Put the polymorphism in the parts. Each kind of part has an interface that doesn’t need to be tailored to use (i.e. no added public features in sub-classes). When the object of which these polymorphic things are a part needs to change its behaviour, swap out one part for another.
The overall object’s interface didn’t change, but its behaviour does.
Read the full article here -https://asifulhaque.com/oop-basics-polymorphism-explained