next up previous contents
Next: Encapsulation:Keeping Code and Data Up: Objects in Perl Previous: Abtraction

Polymorphism:Overriding Methods

Polymorphism is just a little more complicated than inheritance because it involves methods. Earlier, I said you might not learn about methods before you look at a real object-oriented Perl program, but I changed my mind. Let's make up some methods that belong in an inventory program. How about a method to print the properties for debugging purposes or a method to change the quantity-on-hand amount? Figure 14.4 shows the Inventory_item class with these two functions.

The Inventory_item class with methods

This new function is automatically inherited by the PEN class. However, you will run into a problem because the printProperties() function won't print the ink color. You have three choices:

Perl's take on polymorphism is that if you call a method in your program, either the current class or a parent class should have defined that method. If the current class has not defined the method, Perl looks in the parent class. If the method is still not found, Perl continues to search the class hierarchy.

I can hear you groaning at this point-another object-oriented word! Yes, unfortunately. But at least this one uses the normal, everyday definition of the word. A hierarchy is an organized tree of information. In our examples so far, you have a two-level hierarchy. It's possible to have class hierarchies many levels deep. In fact, it's quite common. Figure 14.5 shows a class hierarchy with more than one level.

A class hierarchy with many levels

It's probably worth mentioning that some classes contain only information and not methods. As far as I know, however, there is no special terminology to reflect this. These information-only classes may serve as adjunct or helper classes.


next up previous contents
Next: Encapsulation:Keeping Code and Data Up: Objects in Perl Previous: Abtraction
dave@cs.cf.ac.uk