Inheritance with an Example using Perl
Inheritance:
Inheritance is nothing but inheriting methods/properties from Parent class to child class.
Inheritance is one of main pillars of Object Oriented Concepts.
Inheritance in Perl :
In Perl, inheritance is accomplished by placing the names of parent classes into a special array called @ISA
The elements of @ISA are searched left to right for any missing methods.
E.g.,
our @ISA = qw(AAA BBB);
#This represents we are inheriting from Packages AAA and BBB respectively.
Lets define with an example as mentioned below :
Inventory.pm (Parent of Pen)
Pen.pm (Pen inherits methods from Inventory)
main.pl (Create instance of Pen and accessing the methods of Inventory class as well)
Inventory.pm
#!/usr/bin/perl package Inventory; use strict; use warnings; use Data::Dumper; sub new { my($class) = shift; my(%params) = @_; bless { "NUMBER" => $params{"NUMBER"}, "QUANTITY" => $params{"QUANTITY"} }, $class; } 1;
Pen.pm
#!/usr/bin/perl package Pen; use strict; use warnings; use Data::Dumper; use Inventory; our @ISA = qw(Inventory); #### Inheritance sub new { my($class) = shift; my(%params) = @_; #my($self) = Inventory->new(@_); my($self) = new Inventory(@_); $self->{"COLOR"} = $params{"COLOR"}; return(bless($self, $class)); } 1;
main.pl
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use Pen; my $pen = new Pen( "NUMBER" => "12A-34", "QUANTITY" => 34, "COLOR" => "blue" ); print("The part number is " . $pen->{'NUMBER'} . "\n"); print("The quantity is " . $pen->{'QUANTITY'} . "\n"); print("The ink color is " . $pen->{'COLOR'} . "\n");
Output:
The part number is 12A-34 The quantity is 34 The ink color is blue
No comments:
Post a Comment