One reader, Dave
wrote in and said, "Your description of Polymorphism is wrong. I will attempt
to clarify. Please excuse the nature of my opening sentence. I hoped to
get your attention so I can help (not criticize) to avoid misleading your
readers regarding your Java tutorial.
In a nutshell, polymorphism is bottom-up method calling. Simply put,
using your Animal/Mammal/Cat example:
void test()
{
Cat simon = new Cat();
Animal creature = simon; // safe upcasting
creature.eat(); // polymorph = Cat.eat()
Dog rover = new Dog();
// rover safely upcast to Animal reference
feed(rover);
feed(simon);
}
void feed(Animal a )
{
// creature.eat() = Cat.eat()
// feed(rover) = Dog.eat()
// feed(simon) = Cat.eat()
a.eat();
}
Here, it's the Animal.eat() which is polymorphic.
Polymorphism: "Calling a Java/virtual method using a reference to a
more generalized superclass of a real object invokes the method in the
actual object (the more specific subclass) using a bottom-up searching
mechanism".
Your Java Tutorial's definition of polymorphism states that function
name overloading is the same thing, which is an incorrect statement."
I have to say that Dave is correct, however, I want to focus on overloading
here, so I hope to make both points by adding this note! |