Suppose that you've created a class, and another class that
inherits from the original class. You want to construct a
new object from your subclass, but you want it to inherit
the data fields of its superclass. So, in the constructor
of your subclass, you want to call the constructor in your
superclass. How do you do that?
Perl has a very nice and easy way of doing this: use the
SUPER pseudo-class, which tells Perl to look for the method
that you're calling in any of the superclasses.
So you define your superclass--for example, we'll define
the following Person class:
package Person;
sub new {
my $type = shift;
my $class = ref $type || $type;
my $self = { @_ };
bless $self, $class;
$self;
}
sub name { shift->{NAME} }
And then you have a class Male that inherits from
Person:
package Male;
@Male::ISA = qw/Person/;
sub new {
my $type = shift;
my $class = ref $type || $type;
my $self = $class->SUPER::new(@_);
$self->{GENDER} = "male";
$self;
}
sub gender { shift->{GENDER} }
Simple! All we had to do was call the SUPER constructor
to get back a new object: the new object is blessed
into our "Male" class, but it contains all of the
initialized data fields from our Person class, as well.
Here we have a little test program to test it out:
package main;
my $him = new Male(NAME => "Foo Bar");
print "\$him is in the class '", ref $him, "'\n";
print $him->name, " is of the gender ", $him->gender, "\n";
and we get
$him is in the class 'Male'
Foo Bar is of the gender male
Which is what we expected.
For more information, take a look at perlbot and
perlboot. |