Monday, April 16, 2012

Constructor overloading in Perl

Base Class:
-----------

#!/usr/bin/perl
use strict;
use Data::Dumper;

#write package name:
package Person;

#write constructor
sub new
{
#declare => hash & bless it and return it.
my($class)=shift;
my($self)={
        _name=>shift,
        _sname=>shift,
};
bless $self, $class;
return $self;
}

1;
 
Derived class:
--------------

#!/usr/bin/perl

#define package:
package Employee;

use strict;
use Data::Dumper;

#use parent class
use Person;

#Define ISA
our @ISA = qw(Person);

#Define constructor with child and parent both:
sub new
{
my($class)=@_;
my($self)=$class->SUPER::new($_[1],$_[2]);
$self->{_id} = $_[3];
$self->{_sal} = $_[4];

return ($self);
}

1;

Program:
--------

use strict;
use Data::Dumper;

use Person;
use Employee;

sub main
{
my($obj)=Employee->new("mandar","pande","111515","1");
print "$obj->{_name}\n";
print "$obj->{_sname}\n";
print "$obj->{_id}\n";
print "$obj->{_sal}\n";
}

main();

No comments:

Post a Comment