If I want to instantiate an object, but don't know whether I have a Sedan or an SUV, can I ask the base class to figure that out for me and return the right object?
You certainly can.
Is that good practice?
This probably debatable. From a theoretical perspective, a parent class should not depend on its child classes, just the other way. Or formulated differently, you want to avoid cycles in your dependency graphs.
From a practical point of view, there often needs to be some piece of code that needs to create as-specific-as-possible objects. Why not have put it in the parent class?
An approach I found practical is to have some kind of "type registry", which is usually just a hash. On object creation, some kind of key looks into the hash, and then simply re-dispatches to new method of that type.
package Car; has %car_by_type; sub new { my ($self, %opts) = @_; if ($opts{name} && $car_by_type{$opts{name}}) { $car_by_type{$opts{name}}->new(%opts); } else { die "Don't know how to make a new car"; } } method REGISTER_TYPE { my ($self, $name, $type) = @_; $car_by_type{$name} = $type; } package Car::BMW; our @ISA = qw/Car/; Car::BMW->REGISTER_TYPE('Z1', __PACKAGE__); Car::BMW->REGISTER_TYPE('Z3', __PACKAGE__); package main; my $z1 = Car->new(name => 'Z1');
(untested)
In reply to Re: Inheritance: parent class determine which child class to use?
by moritz
in thread Inheritance: parent class determine which child class to use?
by fbicknel
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |