It matters who knows these constants. If these are only known in the "final" classes, then you can use a single do_something() inherited from the parent class, and then arrange for each of the specializing classes to provide methods to return the constants.
Let's consider a simple "B inherits from A" case.
This adapts easily to multiple levels of inheritance. For example, the first level of inheritance can override x() and the next level can override y().package A; sub new { my $pkg = shift; bless {}, $pkg; } sub do_something { my $self = shift; my $n = $self->x() + $self->y(); print "something is $n\n"; } sub x { die "subclass must override x\n" } sub y { die "subclass must override y\n" } package B; @ISA = (A); sub x { 42 } sub y { 47 } package main; my $object = new B(); $object->do_something; # A::do_something invokes B::x and B::y
An alternative is to stuff the constants into the object's hash at initialization time.
In both cases, you could provide default behavior in the superclass.package A; sub new { my $pkg = shift; my $self = bless {}, $pkg; $self->init(); } sub init { die "subclass must override init()\n" } sub do_something { my $self = shift; my $n = $self->{x} + $self->{y}; print "something is $n\n"; } package B; @ISA = (A); sub init { my $self = shift; $self->{x} = 42; $self->{y} = 47; } package main; my $object = new B(); $object->do_something(); # A::do_something reaches into the bag, and pulls out # numbers that B::init provided
In reply to Re: Re: Re: Trying to re-use code at different levels of an inherited object.
by dws
in thread Trying to re-use code at different levels of an inherited object.
by ehdonhon
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |