btrott has asked for the wisdom of the Perl Monks concerning the following question:

This was originally posted as a Categorized Question.

Replies are listed 'Best First'.
Answer: How do I call an overridden method?
by btrott (Parson) on Apr 21, 2000 at 02:05 UTC
    Suppose that you've created a class, and another class that inherits from the original class. You want to construct a new object from your subclass, but you want it to inherit the data fields of its superclass. So, in the constructor of your subclass, you want to call the constructor in your superclass. How do you do that?

    Perl has a very nice and easy way of doing this: use the SUPER pseudo-class, which tells Perl to look for the method that you're calling in any of the superclasses.

    So you define your superclass--for example, we'll define the following Person class:

    package Person; sub new { my $type = shift; my $class = ref $type || $type; my $self = { @_ }; bless $self, $class; $self; } sub name { shift->{NAME} }
    And then you have a class Male that inherits from Person:
    package Male; @Male::ISA = qw/Person/; sub new { my $type = shift; my $class = ref $type || $type; my $self = $class->SUPER::new(@_); $self->{GENDER} = "male"; $self; } sub gender { shift->{GENDER} }
    Simple! All we had to do was call the SUPER constructor to get back a new object: the new object is blessed into our "Male" class, but it contains all of the initialized data fields from our Person class, as well.

    Here we have a little test program to test it out:

    package main; my $him = new Male(NAME => "Foo Bar"); print "\$him is in the class '", ref $him, "'\n"; print $him->name, " is of the gender ", $him->gender, "\n";
    and we get
    $him is in the class 'Male' Foo Bar is of the gender male
    Which is what we expected.

    For more information, take a look at perlbot and perlboot.

Answer: How do I call an overridden method?
by no_slogan (Deacon) on Jun 12, 2001 at 22:22 UTC
    SUPER is good, as btrott points out. You can also get more control, if you need it.
    $o = Foo::Bar::Baz->new(); $o->blat($x); # Foo::Bar::Baz::blat? $o->SUPER::blat($x); # Foo::Bar::blat? Foo::Bar::blat($o, $x); Foo::blat($o, $x);
    This makes your code more dependent on the exact inheritance details of Foo::Bar::Baz, which is not a good thing if someone decides to change things around a little bit. If you find yourself doing this, take a step back and ask yourself if there is a better way.
A reply falls below the community's threshold of quality. You may see it by logging in.