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.


In reply to Answer: How do I call an overridden method? by btrott

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.