in reply to Re: Inherit only few methods from a parent class
in thread Inherit only few methods from a parent class

I don't like that construction. If the "risky" methods are used in the parent class, the inheriting child class may die unexpectedly:

#!/usr/bin/perl -w use strict; package ParentClass; sub new { my $class=shift; return bless {},$class; } sub run { my $self=shift; $self->hello(); $self->risky(); $self->world(); } sub hello { print "*** Hello "; } sub risky { print "risky "; } sub world { print "world! ***\n"; } package ChildClass; our @ISA=qw(ParentClass); sub risky { die "You're not allowed to call risky()"; } package main; $|=1; print "ParentClass:\n"; my $p=ParentClass->new(); $p->run(); print "ChildClass:\n"; my $c=ChildClass->new(); $c->run();

The only clean solution is to have a common base class without the "risky" methods:

#!/usr/bin/perl -w use strict; package BaseClass; sub new { my $class=shift; return bless {},$class; } sub hello { print "*** Hello "; } sub world { print "world! ***\n"; } package FormerParentClass; our @ISA=qw(BaseClass); sub risky { print "risky "; } sub run { my $self=shift; $self->hello(); $self->risky(); $self->world(); } package FormerChildClass; our @ISA=qw(BaseClass); sub run { my $self=shift; $self->hello(); $self->world(); } package main; $|=1; print "FormerParentClass:\n"; my $p=FormerParentClass->new(); $p->run(); print "FormerChildClass:\n"; my $c=FormerChildClass->new(); $c->run();

Alexander

--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

Replies are listed 'Best First'.
Re^3: Inherit only few methods from a parent class
by JavaFan (Canon) on Jul 14, 2009 at 21:12 UTC
    If the "risky" methods are used in the parent class, the inheriting child class may die unexpectedly
    I agree with everything above, except the word unexpectedly. Yes, it will die. On purpose. Because the OP does not want those methods be callable. And if the Parent class calls those subs as methods, it's calling them on objects of type Child. Which the OP doesn't want. Hence death.

      Let's say "dies unexpectedly for the OP". I had and still have the impression that the OP hasn't completely understood inheritance yet.

      If the OP would show us some code, and explain why (s)he thinks that some methods in the parent class are risky, we could do much more than just guessing.

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)