Inheritance
Explore how inheritance works in Perl.
We'll cover the following...
Overview
Perl’s object system supports inheritance, which establishes a parent and child relationship between two classes such that a child specializes its parent. The child class behaves the same way as its parent—it has the same number and types of attributes and can use the same methods. It may have additional data and behavior, but we may substitute any instance of a child where code expects its parent. In one sense, a subclass provides the role implied by the existence of its parent class.
Consider a LightSource
class that provides two public attributes (enabled
and candle_power
) and two methods (light
and extinguish
):
package LightSource {use Moose;has 'candle_power',is => 'ro',isa => 'Int',default => 1;has 'enabled', is => 'ro',isa => 'Bool',default => 0,writer => '_set_enabled';sub light {my $self = shift;$self->_set_enabled( 1 );}sub extinguish {my $self = shift;$self->_set_enabled( 0 );}}
Lines 7–10: Note that the writer
option of enabled
creates a private accessor usable within the class to set the value.
Note: Should we use roles or inheritance? Roles provide composition-time safety, better type checking, better factoring of code, and ...