Monday, June 20, 2011

Inheritance in perl example

Kindly understand the class in Perl means Package.

In case of perl,inheritance takes place by @ISA variable.
Here the classes from which a package has to inherit can be assigned to the @ISA variable.
When object belonging to the class comes across a method call it first searches in the current class(package),if not available it searches in the class specified in the @ISA variable left to right.
If not found also in the @ISA variable ,then only throws a error.
In case of Perl,multiple inheritance is also possible.

Take this perl program for example:

#here the package A has the new constructor which is responsible for creating the Perl object.Here it creates #anonymous hash by using "{}" and blessing into package which comes through shift.
#it also has a subroutine A_method
package A;
sub new { bless {}, shift };
sub A_Method {
print "A_Method\n";

package B;
#here the inherutance is defined and @ISA of package B is assigned to A.This makes Package B to inherit
# from A.It has two sub-routines.
sub B_Method {
print "B_Method\n";
sub Method {
print "Method (in B)\n";

package C;
#here @ISA is assigned to B. Now the Package C inherits both from B and A as B inherits from A.It also #has two subroutines.
@ISA = qw(B);
sub C_Method{
print "C_Method\n";
sub Method {
print "Method (in B)\n";

package main;
# By this method a object reference of the package is returned.
$a = new A;
#here the method first gets converted into  A::new(A) in the format of class::Method('class','arg1','arg2')
#here the new method of Package A is inherited to return the object reference for B.
$b=new B;
#here the new method of Package A is inherited to return the object reference for B.
$c=new C;
$c->C_Method(); #here it calls C_Method of class C
$c->Method();  #here it calls Method of class C
$c->B_Method();#here it calls inherited B_Method of class B
$b->A_Method();#here it calls inherited A_Method of class A
$a->B_Method();#returns a fatal error as the Object A does not inherit B.


Method (in B)
Can't locate object method "B_Method" via package "A" at line 43.

For better understanding also refer to the below program.

Here there are two Classes Person and Student.
The Package Student inherits the new sub-routine of Class Person to define a Student.

package Person;
sub new
my $pkg=shift;
bless{ @_ },$pkg;
package Student;
# here the Student inherits the Person Package.
$ddd=new Person(name=>"jjjjj",age=>55);
$aaa=new Student(name=>'ssss',id=>55,class=>"tenth");
print $ddd->{name}; # here it prints the name of the Person
print $aaa->{name}; # here it prints the name of the Student.



No comments:

Post a Comment