4.1 Inheritance

You've seen the use of modules and how a Perl program can use all the code in a module by simply loading it with the use command. This is a simple and powerful method of software reuse, by which software can be written once but used many times by different programs.

You've also seen how object-oriented Perl defines classes in terms of modules, and how the use of classes, methods, and objects provides a more structured way to reuse Perl software.

There's another way to reuse Perl classes. It's possible for a class to inherit all the code and definitions of another base class. (This base class is sometimes called a superclass or a parent class.) The new derived class (a.k.a. subclass) can add more definitions or redefine certain definitions. Perl then automatically uses the definitions of everything in the old class (but treats them as if they were defined in this new derived class), unless it finds them first in the derived class.

In this chapter, I'll first develop a class FileIO.pm, and then use the technique of inheritance to develop another class SeqFileIO.pm that inherits from FileIO.pm. This way of reusing software by inheritance is extremely convenient when writing object-oriented software. For instance, I make SeqFileIO do a lot of its work simply by inheriting the base class FileIO and then adding methods that handle sequence file formats. I could use the same base class FileIO to write a new class that specializes in handling HTML files, microarray datafiles, SNP database files, and so on. (See the exercises at the end of the chapter.)

When inheriting a class, it is sometimes necessary to do a bit more than just add new methods. In the SeqFileIO class, I add some attributes to the object, and as a result the hash %_attribute_properties also has to be changed. So in the new class I define a new hash with that name, and as a result the old definition from the base class is forgotten and the new, redefined hash is used. As you read the new class, compare it with the base class FileIO. Make note of what is new in the class (e.g., the various put methods), what is being redefined from the base class (e.g., the hash just mentioned), and what is being inherited from the base class (e.g., the new constructor.) This can help prepare you to write your own class that uses inheritance.

Occasionally, you want to invoke a method from a base class that has been overridden. You can use the special SUPER class for that purpose. I don't use that in the code for this chapter, but you should be aware that it is possible to do.