Download presentation
Presentation is loading. Please wait.
Published byRobyn Cooper Modified over 9 years ago
1
Topic 11: Object-oriented Perl CSE3395 Perl Programming Camel3 chapter 12, pages 308-346 perlobj, perltoot, perlbot, perlmod manpages
2
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 2 In this topic Classes as modules Defining methods ► object methods ► class methods ► constructors ► destructors Creating objects ► bless keyword Inheritance ► @ISA array ► polymorphism Comparison with other OO languages ► Java, C++ Classes as modules Defining methods ► object methods ► class methods ► constructors ► destructors Creating objects ► bless keyword Inheritance ► @ISA array ► polymorphism Comparison with other OO languages ► Java, C++
3
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 3 Additional information about OO Advanced Perl Programming ► chapters 6-8 Object-oriented Perl ► by Damian Conway ► Manning Press, first edition 2000 manpages ► perlmod –about packages and modules ► perltoot –Tom’s object-oriented tutorial; simpler introduction to OO Perl ► perlobj –official reference, complete but terse ► perlbot –Bag of Object Tricks; some more complex OO stuff Advanced Perl Programming ► chapters 6-8 Object-oriented Perl ► by Damian Conway ► Manning Press, first edition 2000 manpages ► perlmod –about packages and modules ► perltoot –Tom’s object-oriented tutorial; simpler introduction to OO Perl ► perlobj –official reference, complete but terse ► perlbot –Bag of Object Tricks; some more complex OO stuff
4
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 4 Object-orientation A class is a description of a type of thing An object is an instance of a class A method is a function that operates on a class or object ► class methods (static methods) apply to the class as a whole ► object methods (instance methods) apply to one object A constructor is a method called at object creation A destructor is a method called at object destruction Inheritance is the is-a relationship between two classes ► describes default behaviour of a class ► derived class inherits from base class Polymorphism is the selection of the correct derived method based on the class of the object A class is a description of a type of thing An object is an instance of a class A method is a function that operates on a class or object ► class methods (static methods) apply to the class as a whole ► object methods (instance methods) apply to one object A constructor is a method called at object creation A destructor is a method called at object destruction Inheritance is the is-a relationship between two classes ► describes default behaviour of a class ► derived class inherits from base class Polymorphism is the selection of the correct derived method based on the class of the object
5
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 5 Object-orientation in Perl A class is a description of a type of thing ► in Perl, class is a module An object is an instance of a class ► in Perl, object is a (usually anonymous) value ► object is identified by reference to value ► object looks like a scalar A method is a function that operates on a class or object ► in Perl, method is a subroutine in the module A constructor is a method called at object creation ► in Perl, constructor is a kind of object method which returns a (blessed) object A class is a description of a type of thing ► in Perl, class is a module An object is an instance of a class ► in Perl, object is a (usually anonymous) value ► object is identified by reference to value ► object looks like a scalar A method is a function that operates on a class or object ► in Perl, method is a subroutine in the module A constructor is a method called at object creation ► in Perl, constructor is a kind of object method which returns a (blessed) object Camel3 page 310; perlobj manpage
6
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 6 Using an OO module use Class; ► use Car; Everything else depends on class’ documentation To call a class method: Class->cmethod(args) ► $vehicle = Car->new("ABC123"); ► new() is class method, doesn’t apply to any specific Car (yet) ► new() returns an object (i.e., constructor) –$vehicle is (a reference to) a Car object ► nothing special about name “new”, unlike Java/C++ To call an object method: $object->omethod(args) ► $odometer = $vehicle->odometer(); ► odometer() is object method, applies to a specific Car use Class; ► use Car; Everything else depends on class’ documentation To call a class method: Class->cmethod(args) ► $vehicle = Car->new("ABC123"); ► new() is class method, doesn’t apply to any specific Car (yet) ► new() returns an object (i.e., constructor) –$vehicle is (a reference to) a Car object ► nothing special about name “new”, unlike Java/C++ To call an object method: $object->omethod(args) ► $odometer = $vehicle->odometer(); ► odometer() is object method, applies to a specific Car Camel3 pages 311-313; perlobj, perltoot manpages
7
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 7 Writing an OO module Create a package named for the class ► package Car; For every method, create a subroutine ► sub new {... } ► sub odometer {... } ► class and object methods declared the same way End the method with true value ► 1; Save in module called Class.pm Create a package named for the class ► package Car; For every method, create a subroutine ► sub new {... } ► sub odometer {... } ► class and object methods declared the same way End the method with true value ► 1; Save in module called Class.pm
8
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 8 Writing a class method To write a class method, declare subroutine ► sub new { First parameter ( $_[0] ) is class name (string) ► usually same as current class, but could be derived class if it inherited method from current class ► my $classname = shift; Remaining parameters are arguments from caller ► my ($plate) = @_; To write a class method, declare subroutine ► sub new { First parameter ( $_[0] ) is class name (string) ► usually same as current class, but could be derived class if it inherited method from current class ► my $classname = shift; Remaining parameters are arguments from caller ► my ($plate) = @_;
9
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 9 Writing a constructor Constructor usually a class method To create an object: ► allocate the object’s storage, usually an anonymous hash –my $auto = { }; ► initialize the object with its default values –$auto->{"plate"} = $plate; –$auto->{"ident"} = create_identification(); –$auto->{"odo"} = 0; ► mark the object as belonging to a class using bless keyword –bless $auto, $classname; –bless allows Perl to know which module contains the right subroutine when invoking an object method ► return the reference to caller –return $auto; Constructor usually a class method To create an object: ► allocate the object’s storage, usually an anonymous hash –my $auto = { }; ► initialize the object with its default values –$auto->{"plate"} = $plate; –$auto->{"ident"} = create_identification(); –$auto->{"odo"} = 0; ► mark the object as belonging to a class using bless keyword –bless $auto, $classname; –bless allows Perl to know which module contains the right subroutine when invoking an object method ► return the reference to caller –return $auto; Camel3 pages 317-318
10
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 10 Timeout # Typical constructor (example of object method). package Car; # Constructor new(plate) # Create and return a new car with specified number plate. sub new { my $classname = shift; my ($plate) = @_; my $auto = { plate => $plate, ident => create_identification() odo => 0, # Lifetime odometer trip => 0 # Trip odometer }; bless $auto, $classname; return $auto; } # Typical constructor (example of object method). package Car; # Constructor new(plate) # Create and return a new car with specified number plate. sub new { my $classname = shift; my ($plate) = @_; my $auto = { plate => $plate, ident => create_identification() odo => 0, # Lifetime odometer trip => 0 # Trip odometer }; bless $auto, $classname; return $auto; }
11
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 11 Writing an object method To write a object method, declare subroutine ► sub odometer { First parameter ( $_[0] ) is object (reference to blessed value) ► my $self = shift; ► no special self or this pointer/reference Remaining parameters are arguments from caller ► my ($trip, $reset) = @_; To write a object method, declare subroutine ► sub odometer { First parameter ( $_[0] ) is object (reference to blessed value) ► my $self = shift; ► no special self or this pointer/reference Remaining parameters are arguments from caller ► my ($trip, $reset) = @_;
12
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 12 Timeout # Typical object method. package Car; use Carp; # For croak() function below. # Object method odometer(trip, reset) # Return either the lifetime (0) or trip (1) odometer, # and optionally reset it (trip odometer only). sub odometer { my $self = shift; my ($trip, $reset) = @_; # croak() is like built-in die() but reports error from # perspective of caller. croak("Tried to reset lifetime odometer") if $reset && !$trip; my $result = $self->{ $trip ? "trip" : "odo" }; $self->{"trip"} = 0 if $reset; return $result; } # Typical object method. package Car; use Carp; # For croak() function below. # Object method odometer(trip, reset) # Return either the lifetime (0) or trip (1) odometer, # and optionally reset it (trip odometer only). sub odometer { my $self = shift; my ($trip, $reset) = @_; # croak() is like built-in die() but reports error from # perspective of caller. croak("Tried to reset lifetime odometer") if $reset && !$trip; my $result = $self->{ $trip ? "trip" : "odo" }; $self->{"trip"} = 0 if $reset; return $result; }
13
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 13 Destructors Destructor is called automatically when object falls out of scope ► i.e., its reference count falls to zero ► not called explicitly In Perl, destructor is method called DESTROY (all capitals) Seldom needed because Perl manages memory allocation Some uses ► to keep track of class meta-data ► to dump persistent objects to disk ► to close a file or network connection Destructor is called automatically when object falls out of scope ► i.e., its reference count falls to zero ► not called explicitly In Perl, destructor is method called DESTROY (all capitals) Seldom needed because Perl manages memory allocation Some uses ► to keep track of class meta-data ► to dump persistent objects to disk ► to close a file or network connection Camel3 pages 330-331
14
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 14 Inheritance A class can derive from one or more parent classes by setting the @ISA array ► package SportsCar; @ISA = qw(Car StatusSymbol); ► Any method not found in class SportsCar will now fall back to the same-named methods in Car and StatusSymbol ► This is how Exporter.pm module works –@ISA = qw(Exporter); # Inherit export() ► Can delegate to superclass (parent) with special SUPER:: class name –skips current class when dispatching method –$self->SUPER::method() A class can derive from one or more parent classes by setting the @ISA array ► package SportsCar; @ISA = qw(Car StatusSymbol); ► Any method not found in class SportsCar will now fall back to the same-named methods in Car and StatusSymbol ► This is how Exporter.pm module works –@ISA = qw(Exporter); # Inherit export() ► Can delegate to superclass (parent) with special SUPER:: class name –skips current class when dispatching method –$self->SUPER::method() Camel3 pages 321-326; perlobj manpage
15
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 15 Polymorphism All method calls are dispatched at runtime in Perl Method dispatch is based on ► class that object was blessed into ► name of method All methods are by default polymorphic All method calls are dispatched at runtime in Perl Method dispatch is based on ► class that object was blessed into ► name of method All methods are by default polymorphic
16
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 16 Timeout package Random; # new(n): create n-sided Random object. sub new { my $class = shift; my $self = { range => $_[0] }; return bless $self, $class; } # toss(): return result from 1 to object's range. sub toss { my $self = shift; $self->{"tosses"}++; # Count tosses. return int (rand $self->{"range"}) + 1; } sub DESTROY { my $self = shift; print "Did ", $self->{"tosses"}, " tosses on ", $self->{"range"}, "-sided\n" } 1; package Random; # new(n): create n-sided Random object. sub new { my $class = shift; my $self = { range => $_[0] }; return bless $self, $class; } # toss(): return result from 1 to object's range. sub toss { my $self = shift; $self->{"tosses"}++; # Count tosses. return int (rand $self->{"range"}) + 1; } sub DESTROY { my $self = shift; print "Did ", $self->{"tosses"}, " tosses on ", $self->{"range"}, "-sided\n" } 1;
17
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 17 Timeout package Die; use Random; @ISA = qw(Random); # Inherit from Random. # Introduce roll() as synonym for toss() sub roll { my $self = shift; return $self->toss(@_); } 1; package Die; use Random; @ISA = qw(Random); # Inherit from Random. # Introduce roll() as synonym for toss() sub roll { my $self = shift; return $self->toss(@_); } 1;
18
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 18 Timeout package Coin; use Random; @ISA = qw(Random); # new(): make a coin object. Coins are 2-sided. sub new { my $class = shift; $class->SUPER::new(2); # Delegate to parent class, 2 sides. } # toss(): return "heads" or "tails" sub toss { my $self = shift; return $self->SUPER::toss(@_) == 1 ? "heads" : "tail"; } 1; package Coin; use Random; @ISA = qw(Random); # new(): make a coin object. Coins are 2-sided. sub new { my $class = shift; $class->SUPER::new(2); # Delegate to parent class, 2 sides. } # toss(): return "heads" or "tails" sub toss { my $self = shift; return $self->SUPER::toss(@_) == 1 ? "heads" : "tail"; } 1;
19
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 19 Timeout #!/usr/bin/perl -w use Die; use Coin; $c = Coin->new(); $d6 = Die->new(6); $d10 = Die->new(10); # Do it 100 times. foreach (1.. 100) { print $c->toss(), " ", $d6->roll() + $d10->roll(), "\n"; } #!/usr/bin/perl -w use Die; use Coin; $c = Coin->new(); $d6 = Die->new(6); $d10 = Die->new(10); # Do it 100 times. foreach (1.. 100) { print $c->toss(), " ", $d6->roll() + $d10->roll(), "\n"; }
20
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 20 OO in Perl, Java and C++ Underlying representation ► Perl: anonymous hash/array/scalar, looked up by reference ► C++, Java: opaque structure similar to a C struct Object methods and class methods ► Perl: equivalent syntax, distinguished by use ► C++, Java: class methods denoted by static keyword Class data ► Perl: package-level global variables ► C++, Java: variables defined with static keyword Underlying representation ► Perl: anonymous hash/array/scalar, looked up by reference ► C++, Java: opaque structure similar to a C struct Object methods and class methods ► Perl: equivalent syntax, distinguished by use ► C++, Java: class methods denoted by static keyword Class data ► Perl: package-level global variables ► C++, Java: variables defined with static keyword
21
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 21 OO in Perl, Java and C++ Instance data ► Perl: stored as key/value in object hash ► C++, Java: stored in opaque structure Constructors ► Perl: a class method, called explicitly; must allocate object and initialize it; can have any name ► C++, Java: not strictly a method, called implicitly; need only initialize the object; new keyword has special meaning for object construction Destructors ► Perl, C++, Java: an object method, invoked implicitly when object falls out of scope Instance data ► Perl: stored as key/value in object hash ► C++, Java: stored in opaque structure Constructors ► Perl: a class method, called explicitly; must allocate object and initialize it; can have any name ► C++, Java: not strictly a method, called implicitly; need only initialize the object; new keyword has special meaning for object construction Destructors ► Perl, C++, Java: an object method, invoked implicitly when object falls out of scope
22
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 22 OO in Perl, Java and C++ Inheritance ► Perl, C++: multiple, using @ISA (Perl) and :public Base (C++); no difference between inheritance and interfaces ► Java: single, using extends ; multiple inheritance approximated with interfaces Polymorphism ► Perl, Java: applies to all method calls, runtime dispatch ► C++: disabled (compile-time dispatch) unless method declared with virtual keyword Access control ► Perl: none, relies on programmer to honour documented interface ► C++, Java: enforced at compile time with public, private and protected keywords; C++ has friend keyword Inheritance ► Perl, C++: multiple, using @ISA (Perl) and :public Base (C++); no difference between inheritance and interfaces ► Java: single, using extends ; multiple inheritance approximated with interfaces Polymorphism ► Perl, Java: applies to all method calls, runtime dispatch ► C++: disabled (compile-time dispatch) unless method declared with virtual keyword Access control ► Perl: none, relies on programmer to honour documented interface ► C++, Java: enforced at compile time with public, private and protected keywords; C++ has friend keyword
23
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 23 OO in Perl, Java and C++ Method overloading ► Perl: none, only one method with each name ► C++/Java: all parameter types contribute to method signature Operator overloading ► Perl, C++: yes, with use overload (Perl) and operator+ (etc.) methods (C++); infix/prefix notation converted to method calls ► Java: none Method overloading ► Perl: none, only one method with each name ► C++/Java: all parameter types contribute to method signature Operator overloading ► Perl, C++: yes, with use overload (Perl) and operator+ (etc.) methods (C++); infix/prefix notation converted to method calls ► Java: none
24
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 24 Covered in this topic Classes as modules Defining methods ► object methods ► class methods ► constructors ► destructors Creating objects ► bless keyword Inheritance ► @ISA array ► polymorphism Comparison with other OO languages ► Java, C++ Classes as modules Defining methods ► object methods ► class methods ► constructors ► destructors Creating objects ► bless keyword Inheritance ► @ISA array ► polymorphism Comparison with other OO languages ► Java, C++
25
Original Slides by Debbie Pickett, Modified by David Abramson, 2006, Copyright Monash University 25 Going further Operator overloading ► Camel3 chapter 13, pages 347-362 Autoloading ► generation of methods on the fly ► Camel3 pages 296-298 Closures ► another way of doing OO ► Camel3 pages 259-263, 339-342 Operator overloading ► Camel3 chapter 13, pages 347-362 Autoloading ► generation of methods on the fly ► Camel3 pages 296-298 Closures ► another way of doing OO ► Camel3 pages 259-263, 339-342
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.