Search⌘ K
AI Features

Solution Review: Implement Inheritance

Explore how to implement inheritance in Perl with Moose by defining base and derived classes. Understand how to override methods and manage class attributes for efficient object-oriented design.

We'll cover the following...

Solution

Let’s look at the solution before jumping into the explanation:

Perl
package Shape {
use Moose;
sub area {
die "area method must be overridden";
}
}
package Rectangle {
use Moose;
extends 'Shape';
has 'length' => (is => 'rw', isa => 'Num');
has 'width' => (is => 'rw', isa => 'Num');
sub area {
my $self = shift;
return $self->length * $self->width;
}
}
package Circle {
use Moose;
extends 'Shape';
has 'radius' => (is => 'rw', isa => 'Num');
sub area {
my $self = shift;
return 3.1416 * ($self->radius ** 2);
}
}

Explanation

Let's go through the ...