Type Systems Demystified
Written by Nikos Vaggalis   
Friday, 19 February 2010
Article Index
Type Systems Demystified
Late binding
Perl
C# and Reflection
Dynamic typing
Automation and delegates

Object-oriented Perl

In object-oriented Perl the method to be called is always determined at runtime, as Perl methods can work against any class or object. That makes them virtual by default. They are not tied to class or instance thus there is no static or instance method in the classic OOP sense.

The class is actually a package and the object is an anonymous hash structure which has been blessed to the class; this is how a class is instantiated in Perl. Later on when you use an instance to call the method, the instance is passed as the 'this' pointer to the method; the package is 'extracted' from the instance and this piece of data is used to identify which method to call. The same paradigm stands true for class/static methods as the method acts accordingly to the arguments it receives, so classes or instances can call any method.

Example 4

 package Class1;
  sub new {
 my($class) = shift;
 bless {
  "product_name"    => undef,
  "product_serial_number" =>
 undef
 }, $class;
  }
  sub print_my_info {
 my ($self, @args) = @_;
 print "My class is : $self\n"
 print "The arguments
received are : @args\n";
 }
 package Class2;
  sub new {
  my($class) = shift;
  bless {
 "product_info"    => undef,
  "product_cost" => undef
  }, $class;
  }
   sub print_my_info {
my ($self, @args) = @_;
print "My class is : $self\n";
print "The arguments
received are : @args\n";
}
 package Main;\
$obj1=Class1->new();
$obj2=Class2->new();
 $obj1->print_my_info(
"Class1 instance");
$obj2->print_my_info(
"Class2 instance");

The output is :

My class is : Class1=HASH(0x23accc)
The arguments received are :
Class1 instance
My class is : Class2=HASH(0x182afc4)
The arguments received are :
Class2 instance

We create two instances one for Class1 and for Class2. Now when the instance method 'print_my_info' is called the correct binding is taking place based on the 'this' pointer which is passed in as the first argument to the method.

<ASIN:0596520107>

<ASIN:0672327937>

 



Last Updated ( Friday, 09 November 2012 )
 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.