Inheritance
A subclass gets the methods of its parent class and can override or extend them.
In this page:
Inheritance
The use parent pragma sets up inheritance by adding the parent to the subclass's @ISA array, which you could also assign to directly with our @ISA = (Parent). When a method is not found in the object's own class, Perl searches the classes in @ISA. Inside an overriding method, SUPER::method calls the parent's version.
Note:
use parent -norequire, Base is needed when the parent is defined in the same file, because otherwise use parent tries to load a file called Base.pm.
Example: Inheritance
use strict;
use warnings;
package Animal;
sub new {
my ($class, %args) = @_;
my $self = bless { name => $args{name} }, $class;
return $self;
}
sub name { $_[0]{name} }
sub speak { my $self = shift; return $self->name . " makes a sound"; }
package Dog;
use parent -norequire, 'Animal';
sub new {
my ($class, %args) = @_;
my $self = $class->SUPER::new(%args);
$self->{tricks} = [];
return $self;
}
sub speak {
my $self = shift;
return $self->SUPER::speak() . ": Woof!";
}
sub add_trick { my ($self, $t) = @_; push @{ $self->{tricks} }, $t; return $self; }
sub tricks { @{ $_[0]{tricks} } }
package main;
my $animal = Animal->new(name => "Generic");
my $dog = Dog->new(name => "Rex");
print $animal->speak, "\n";
print $dog->speak, "\n";
$dog->add_trick("sit")->add_trick("roll");
print "tricks: ", join(", ", $dog->tricks), "\n";
print "Dog ISA: @Dog::ISA\n";
# Output:
# Generic makes a sound
# Rex makes a sound: Woof!
# tricks: sit, roll
# Dog ISA: Animal
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting -norequire for classes defined in the same file
- Calling the parent's constructor without SUPER::new
- Assuming SUPER refers to the class of the object rather than the package where the call is written
Chapter Summary
- use parent sets @ISA
- Methods are searched in the parents
- SUPER::method calls the parent version
- -norequire skips loading a file
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: