5.6.2.3 Defining a Child Class

5.6.2.3  Defining a Child Class

  Next, in our program, we define a class called Friend. This is a subclass of the Person class. This is indicated by setting a list variable called @ISA in the beginning of a class’s definition. In our case, the statement that establishes this child-parent or is-a relationship is given as

 

@ISA = ("Person");

 

As a result of the fact that the class Person is a parent of the class Friend, all methods in the Person class are inherited by the Friend class unless expressly overridden. In this case, the methods set_name and get_name of the Person class are inherited by the Friend class. However, the constructor method make is not inherited by Friend from Person because Friend defines a make method of its own. When a subclass defines a method of the same name as that of a parent, the inheritance of the method is overridden.

So, we see that the child class Friend has its own make method for constructing its own instances. In the make method in the Friend class, two fields hometown and age are initialized to undef. These are two fields that an instance of Friend has
in addition to the field name that is inherited from the Person class. In this example, we see that although Perl does not allow inheritance of a field or a slot, such inheritance of a field can be effectively implemented by inheriting methods that assign value and access the value of the field.

The Friend class has four other methods or subroutines: set_hometown, get_hometown, set_age and get_age. These are used for setting and accessing the values of the two fields. A sequence of statements that create and assign values to fields of an instance of the Friend class are given below.

 

$tommy = Friend -> make; $tommy -> set_name ("Tommy");

$tommy -> set_hometown ("Washington DC");

$tommy -> set_age (18);

 

$tommy is created as instance of the class Friend by calling the make method of the Friend class. Next, the name field of the instance pointed to by $tommy is set to "Tommy" by the call to the set_name method. We must note that the
set_name method is not actually defined in the Friend class, but is inherited from the Person class. Following this statement, we have two calls to two methods defined in the Friend class, namely, set_hometown and set_age.

At the very end of the program, we print the information contained in the four object instances that the program creates. For example, the information referenced by the $tommy variable is an instance of Friend and this information is printed using

 

printf "%-7s%-15s%d\n", $tommy -> get_name,

       $tommy -> get_hometown, $tommy -> get_age;

 

The output of the program is given below.

 

Ron   

Erin  

Jeff   Boulder        21

Tommy  Washington DC  18