I see in Wikipedia and other text giving examples of polymorphism in this way:
1) If there is an array of 4 Animal objects, and they really are of Bird, Dog, Cat, Fish classes, then looping through them, and calling animal.move()
, (where animal is a generic animal pointer), then that will be polymorphism.
2) If I have a Dog object, but I pass it to a plain function moveIt(Animal *animal)
and inside, it uses animal.move()
to invoke move()
, and we can pass in a Fish object too (by moveIt(fish)
), and it will do the right thing too, and that's polymorphism.
I think that's fine, the examples showed a generic animal object being able to invoke the appropriate method (wisely) as a dog or fish, and that's polymorphism.
But what about in languages such as JavaScript or Ruby, where array elements can be any type at all. So it is not an array of 4 animal objects, but an array of [bird, dog, cat, fish]
, and now we loop through the array and invoke it:
# In Ruby:
bird = Bird.new()
dog = Dog.new()
cat = Cat.new()
fish = Fish.new()
arr = [bird, dog, cat, fish]
arr.each do |i|
i.move()
end
now in this case, since they never became a "generic" animal, and of course we expect dog.move()
to behave as a dog's way of movement, so in this case, strictly speaking, will it still be polymorphism?