in reply to Re^3: Help me understand inheritance please!
in thread Help me understand inheritance please!

How do I use the "has-a" relationship? Say I have a paw object that is used by many of my objects, like the cat object. I'd use it like $cat->paw->scratch, but how would cat.pm use implement the paw.pm?
  • Comment on Re^4: Help me understand inheritance please!

Replies are listed 'Best First'.
Re^5: Help me understand inheritance please!
by BrowserUk (Patriarch) on Nov 05, 2004 at 04:16 UTC

    Has-a relationship methods are generally not directly usable by callers of the delegating class. calling scratch directly on cat doesn't indicate which paw should scratch. Hence, the delegating class has-a method that uses it parameter(s) to determine which instance of paw should do the scratching.

    #! perl -slw use strict; package paw; sub new { my $class = shift; return bless { @_ }, $class; } sub scratch { my $self = shift; print "Scratching with $self->{ which } paw"; } package cat; sub new { my $class = shift; my %self = @_; $self{ paws } = { map{ $_ => paw->new( which => $_ ) } 'left front', 'right front', 'left hind', 'right hind' }; return bless \%self, $class; } sub scratchesWith{ my( $self, $paw ) = @_; $self->{ paws }{$paw}->scratch(); } sub speaks { my $self = shift; print $self->{name}, ' says: ', $self->{voice}; } 1; package main; my $cat = cat->new( name => 'Tiddles', voice=> 'Meow!', ); $cat->scratchesWith( 'right front' ); $cat->speaks(); __END__ [ 4:08:26.92] P:\test>405381 Scratching with right front paw Tiddles says: Meow!

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    "Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon
Re^5: Help me understand inheritance please!
by dragonchild (Archbishop) on Nov 05, 2004 at 03:49 UTC
    $cat would have an internal data structure that would store instances of the paw class. Then, cat's paw() method would return a paw object. Not that hard, once you see it in action once or twice.

    Being right, does not endow the right to be rude; politeness costs nothing.
    Being unknowing, is not the same as being stupid.
    Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
    Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.