Perl: Multilevel inheritance, example

Multilevel inheritance means, a child package has one parent package which itself is a child package of another parent package.

To consider an example you need to create below 4 files.

1) fruit.pm (parent class)

.pm Files are perl’s module files.

2) guava.pm (child class from fruit)

3) bigfruit.pm (child class from guava)

4) core.pl (main executable file which will use only bigfruit class)

After that run the core.pl and observe the output.

———————————————————————————–

#fruit.pm

use strict;

package fruit;
sub new {
my $class = shift;
my $self = {
name => shift,
color => shift,
};
#print “\nName of fruit: $self->{name}\n”;
bless $self, $class;
return $self;
}
1;

———————————————————————————–

———————————————————————————–

#guava.pm

use strict;
use fruit;
package guava;
our @ISA = qw(fruit);

sub new {
my $class = shift ;
my $self = $class ->SUPER::new($_[0],$_[1]) ;
$self->{size} = $_[2];
$self->{taste} = $_[3];

bless $self,$class;
return $self;
}
1;

———————————————————————————–

———————————————————————————–

#bigfruit.pm

use strict;
use guava;

package bigfruit ;
our @ISA=qw (guava);
sub new {
my $class = shift;
my $self = $class->SUPER::new($_[0],$_[1],$_[2],$_[3]);
$self ->{size} = “big”;
bless $self, $class;
return $self;
}
1;

———————————————————————————–

———————————————————————————–

#core.pl

use strict;
use bigfruit;

my $mango= new fruit(“mango”,”yellow”,”small”,”sweet”);

print $mango->{name} ;
print “\t”,$mango->{color} ;
print “\t”,$mango->{size} ;
print “\t”,$mango->{taste} ;

my $mango= new guava(“mango”,”yellow”,”small”,”sweet”);

print “\n”,$mango->{name} ;
print “\t”,$mango->{color} ;
print “\t”,$mango->{size} ;
print “\t”,$mango->{taste} ;

my $f2 = new guava(“guava”,”green”,”small”,”good”);
print “\n”,$f2->{name};
print “\t”,$f2->{color};
print “\t”,$f2->{size};
print “\t”,$f2->{taste};

my $f3 = new bigfruit(“melon”,”green”,”new”,”water”);
print “\n”,$f3->{name};
print “\t”,$f3->{color};
print “\t”,$f3->{size};
print “\t”,$f3->{taste};

—————————————————————————————-

Advertisements

Tags: , , ,

One Response to “Perl: Multilevel inheritance, example”

  1. koolkedar Says:

    Output of the above script is as below:

    mango yellow
    mango yellow small sweet
    guava green small good
    melon green big water

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: