Class Inheritance
As with the rest of Perl’s object system, inheritance of one class by another requires
no special syntax to be added to the language. When you invoke a method
for which Perl finds no subroutine in the invocant’s package, that
package’s @ISA array[146] is examined. This is how Perl implements inheritance: each
element of a given package’s @ISA array
holds the name of another package, which is searched when methods are
missing. For example, the following makes the Horse class a subclass of the Critter class. (We declare @ISA with our
because it has to be a package variable, not a lexical declared with
my.)
package Horse; our @ISA = "Critter";
You might see this with the parent pragma, which handles @ISA for you and loads the parent class at the
same time:
package Horse; use parent qw(Critter);
The parent pragma replaces the
older base pragma, which did the same thing but threw in some fields magic if it thought the superclasses used them. If you
don’t know what that is, don’t worry about it (just use parent):
package Horse; use base qw(Critter);
You should now be able to use a Horse class or object everywhere that a Critter was previously used. If your new class
passes this empty subclass
test, you know that Critter
is a proper base class, fit for inheritance.
Suppose you have a Horse object
in $steed and invoke a move method on it:
$steed–>move(10);
Because $steed is a Horse, Perl’s first choice for that method is
the Horse::move subroutine. If there isn’t one, instead of ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access