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
|
|---|
| 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 | |
by afoken (Chancellor) on Jul 14, 2009 at 21:48 UTC |