Saturday, July 9, 2011

inheritance example 2

Perl Script:

#usr/bin/perl
package Person;
sub new
{
my $pkg=shift;
bless{ @_ },$pkg;
}
package Student;
@ISA=qw(Person);
$ddd=new Person(name=>"jjjjj",age=>55);
$aaa=new Student(name=>'ssss',id=>55,class=>"tenth");
print $ddd->{name};
print $aaa->{name};

Output:

jjjjj
ssss

Inheritance example 1

PERL SCRIPT:

package A;
sub new { bless {}, shift };
sub A_Method {
print "A_Methos\n";
}
package B;
@ISA=qw(A);
sub B_Method {
print "B_Method\n";
}
sub Method {
print "Method (in B)\n";
}
package C;
@ISA = qw(B);
sub C_Method{
print "C_Method\n";
}
sub Method {
print "Method (in B)\n";
}
package main;
$a = new A;
#here the method first converted A::new(A) in the format of class::Method('class','arg1','arg2')
$b=new B;
$c=new C;
$c->C_Method();
$c->Method();
$c->B_Method();h
$c->A_Method();
$a->Method();  # this returns error as  object $a does not contain method Method();

OUTPUT:

g:\perl_programs>perl perlinherit.pl
C_Method
Method (in B)
B_Method
A_Method
Can't locate object method "B_Method" via package "A" at perlinherit.pl line 43.