in reply to overridden method - best way

Your base class should not really have to guess all the future ways in which derived child classes can screw things up :) in the base class, implement the method you want:

package Parent; sub X { my $self = shift @_; print "called Parent::X()\n"; ... } # ------------------- # and in the Child class you specialise this package Child; use base qw(Parent) sub X { my $self = shift @_; $self->SUPER::X(@_); # Call Base class method # then do some extra stuff print "called Child::X()\n"; ... } # ------------------- # and further down the chain... package GrandChild; use base qw(Child) sub X { my $self = shift @_; $self->SUPER::X(@_); # Call up one level # then do some extra grandchild stuff print "called GrandChild::X()\n"; ... }
This works to any depth of inheritance. One of the main benefits of OO is this type of inheritance where you can specialise a child class without having to recode the Parent and causing unanticipated issues elsewhere.

So in my opinion, _Private_X should be court marshalled. I usually find that $obj->can('method') is more suited for use in handling collections of different types of objects. If you are using it for an inheritance hierarchy trick, look again - its probably a mistake.

Regards,

Jeff

Replies are listed 'Best First'.
Re: Re: overridden method - best way
by jaa (Friar) on May 25, 2004 at 18:02 UTC
    Oh - and a little trick I use to prevent private methods from fooling the inheritance chain...
    package Parent; sub X { my $self = shift @_; print "called Parent::X()\n"; ... } # ------------------- # and in the Child class you specialise this package Child; use base qw(Parent) sub X { my $self = shift @_; $self->SUPER::X(@_); # Call Base class method # local function NOT inherited _X($self,@_); ... } sub _X { my $self = shift; print "called Child::_X()\n"; } # ------------------- # and further down the chain... package GrandChild; use base qw(Child) sub X { my $self = shift @_; $self->SUPER::X(@_); # Call up one level # then do some extra grandchild stuff # local function NOT inherited _X($self,@_); ... } sub _X { my $self = shift; print "called GrandChild::X()\n"; }

    Note that I do not want the _X() subs called through the inheritance hierarchy, so I call them directly as functions in the current package.

    Regards,

    Jeff