Perl - Advanced Features of Object Orientation
In a Nutshell - CIW Course Section 2, Part B3, Chapter 4
Scaling Considerations
A class may be used as the base to form another class. With this in mind, the class needs to be designed in such a way that subclasses can inherit meaningful and sensible structures and data.
Object Constructor Inheritance
If a subclass can use the parent class's constructor this will benefit the inheritance of the object. The following example demonstrates the basics:
#!c:\perl\bin\perl.exe
package Foo;
sub new {
my $type = shift;
my $self = {};
return bless $self, $type;
}
sub bar {
print "This is in Foo::bar!\n";
}
package Man;
@ISA = ("Foo");
sub bar {
print "This is in Man::bar!\n";
}
package main;
$a = Man->new;
$a->bar;
$b = Foo->new;
$b->bar;
In the Man package we have added a reference to Foo to the @ISA array. Now when we invoke Man->new there is no sub new in the package, so the interpreter looks to modules listed in the @ISA array to find the next occurrence of a new subroutine.
Object Aggregation
Aggregation is the combining of two or more objects to produce a larger, more complex object. In the following example we are creating a parent object which contains a child object:
#!c:\perl\bin\perl.exe
package Child;
sub new {
my $self = {};
$self->{age} = 4;
return bless $self;
}
package Parent;
sub new {
my $self = {};
$self->{offspring} = new Child();
$self->{age} = 30;
return bless $self;
}
package main;
$mother = new Parent();
print("Mother is: " . $mother->{age} . "\n");
print("Child is: " . $mother->{offspring}->{age} . "\n");
Now, ideally, a parent may have more than one child. So how can we modify the above model to cater for this? Simply put, I have no idea. This would probably require the parent object to contain an array to reference the children, but I don't believe a hash can contain an array. I suppose it could contain an array reference as this is just a scalar value, but how you build this I cannot begin to imagine.

