Accessing Overridden Methods
When a class defines a method, that subroutine overrides methods of the
same name in any base classes. You have the Mule object (which is derived from class
Horse and class Donkey), and you decide to invoke your
object’s breed method. Although the
parent classes have their own breed
methods, the designer of the Mule
class overrode those by supplying the Mule class with its own breed method. That means the following cross
is unlikely to be productive:
$stallion = Horse–>new(gender => "male"); $molly = Mule–>new(gender => "female"); $colt = $molly–>breed($stallion);
Now, suppose that through the miracle of genetic engineering, you
find some way around a mule’s notorious sterility problem, so you want
to skip over the nonviable Mule::breed method. You
could call your method as an ordinary subroutine,
being sure to pass the invocant explicitly:
$colt = Horse::breed($molly, $stallion);
However, this sidesteps inheritance, which is nearly always the
wrong thing to do. It’s perfectly imaginable that no Horse::breed subroutine exists because both
Horses and Donkeys derive that behavior from a common
parent class called Equine. If, on
the other hand, you want to specify that Perl should
start searching for a method in a particular class,
just use ordinary method invocation but qualify the method name with the
class:
$colt = $molly–>Horse::breed($stallion);
Occasionally, you’ll want a method in a derived class to act as a wrapper around some method in a base class. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access