s.patra
s.patra

Reputation: 147

multi-level inheritance in Perl

I have a question related to multi-level inheritance in Perl.

Here is my code

mod.pm

package first;

sub disp {
    print "INSIDE  FIRST\n";
}

package second;
@ISA = qw(first);

sub disp {
    print "INSIDE SECOND\n";
}

package third;
@ISA = qw(second);

sub new {
    $class = shift;
    $ref   = {};
    bless $ref, $class;
    return $ref;
}

sub show {
    $self = shift;
    print "INSIDE THIRD\n";
}

1;

prog.pl

use mod;

$obj = third->new();
$obj->show();
$obj->disp();

I have a .pm file which contains three classes. I want to access the disp method in the first class using an object of third class. I'm not sure how that could work.

I tried to access using two ways:

  1. using class name => first::disp()
  2. using SUPER inside second package disp method => $self->SUPER::disp();

But am not sure how it will be accessed directly using the object of third class.

Upvotes: 3

Views: 358

Answers (2)

Borodin
Borodin

Reputation: 126762

If you need to do that, then you have defined your classes wrongly.

The third class inherits from the second class. second has it's own definition of disp, so it never tries to inherit that method from its superclass first. That means third gets the implementation defined in second

The simple answer would be to call first::disp something else. That way second won't have a definition of the method and inheritance will be invoked again

If you explain the underlying problem, and why you want to ignore an inherited method, then perhaps we can help you find a better way

Please also note that packages and module files should start with a capital letter, and each class is ordinarily in a file of its own, so you would usually use package First in First.pm etc.

Upvotes: 3

ikegami
ikegami

Reputation: 386676

$obj->first::disp(), but what you are asking to do is something you absolutely shouldn't do. Fix your design.

Upvotes: 5

Related Questions