introduction to Perl 5 for web developers Polymorphism Okay, there is one final feature of objects that you need to understand.

Objects are smart enough to be dynamic. Specifically, they have the ability to react differently depending on the situation.

This is important because it makes the API dependable and easy to understand for the incoming developer.

Let's look at an example. Suppose you have a method called "print()".

The first question you might ask is, "what does this method print: pictures, text, or what?"

Well using "polymorphism", an object can be made to handle any scenario with the exact same method name. Thus, depending on what the object is asked to print, it will be able to print it.

Instead of having separate methods like printPicture(), printLetters(), and printNumbers() you have one unified print() and the object itself determines how to handle the different types of situations.

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; // polymorph =
 Dog rover = new Dog();

  // rover safely upcast to Animal reference
void feed(Animal a )
  // =
  // feed(rover)    =
  // feed(simon)    =;

Here, it's the 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!

Previous | Next | Table of Contents