How about the property that the width and height (of a Rectangle) are independent:
package Rectangle;
use Moo;
has height => (is => 'rw');
has width => (is => 'rw');
sub demo {
my ($self) = @_;
printf "Demo of %s\n", ref $self;
$self->show_dimensions;
printf "Resetting height => 4, width => 3\n";
$self->height(4);
$self->width(3);
$self->show_dimensions;
printf "area: %d\n", $self->area;
$self->show_dimensions;
}
sub area {
my ($self) = @_;
$self->{width} * $self->{height};
}
sub show_dimensions {
my ($self) = @_;
printf "height: %s, width: %s\n", $self->{height} || 'undef', $sel
+f->{width} || '';
}
package Square;
use Moo;
extends 'Rectangle';
sub area {
my ($self) = @_;
$self->{height} = $self->{width};
$self->SUPER::area();
}
package main;
my $rect = Rectangle->new(width => 2, height => 2);
my $sq = Square->new(width => 2);
$rect->demo;
print "\n";
$sq->demo;
Which outputs:
Demo of Rectangle
height: 2, width: 2
Resetting height => 4, width => 3
height: 4, width: 3
area: 12
height: 4, width: 3
Demo of Square
height: undef, width: 2
Resetting height => 4, width => 3
height: 4, width: 3
area: 9
height: 3, width: 3
The square fails as a stand-in for a rectangle. The is one of the reasons that wise man say Favor Composition Over Inheritance
|