use strict;
use warnings;
use lib '.';
require Ex::Improved;
my $ex1 = Ex::Improved->new();
# Show that the parent's constructor still works:
my $ex2 = $ex1->new();
$ex1->setColor('green');
$ex1->setFood('bean');
$ex2->setColor('red');
$ex2->setFood('radish');
my $count = 0; # count each object we display
for my $obj ($ex1, $ex2) {
printf "Object: %d\n", ++$count;
printf "Color: %s\n", $obj->getColor();
printf "Food: %s\n", $obj->getFood();
}
####
package Ex::Parent;
use strict;
use warnings;
sub new {
my $class = shift;
# This line lets subclass-created objects work:
$class = ref($class) || $class;
return bless { }, $class;
}
sub getColor {
my $self = shift;
return $self->{color} // undef;
}
sub setColor {
my $self = shift;
$self->{color} = shift or return 0;
return 1;
}
1;
##
##
package Ex::Improved;
use strict;
use warnings;
use parent 'Ex::Parent';
# This "improved" class lets callers get/set Food too!
sub getFood {
my $self = shift;
return $self->{food} // undef;
}
sub setFood {
my $self = shift;
$self->{food} = shift or return 0;
return 1;
}
1;