Object-oriented programming II
#!/usr/local/bin/perl
package Cat;
sub new {
my $class = $_[0];
my $self = {};
bless $self;
$self->{'name'} = $_[1];
$self->{'color'} = $_[2];
return $self;
}
sub meow {
print "meow\n";
}
sub printDetails {
my $self = $_[0];
print "$self->{name}\n";
print "$self->{color}\n";
}
###################################
package main;
my($cat) = new Cat("Fred", "white");
$cat->meow();
$cat->printDetails();
- object or instance: $cat
- class: Cat
- attribute: name, color
- behaviour or methods: new(), meow(), printDetails()
- constructor method: new()
- instance method: printDetails()
- class method: meow()
Exercise
In analogy to the example above, create a package (class) for another
type of pet besides cat or dog (see below).
Encapsulation, inheritance, and polymorphism
#!/usr/local/bin/perl
package Animal;
sub printDetails {
my $self = $_[0];
print "$self->{name}\n";
print "$self->{color}\n";
}
###################################
package Cat;
@ISA = qw(Animal);
sub new {
my $class = $_[0];
my $self = {};
bless $self;
$self->{'name'} = $_[1];
$self->{'color'} = $_[2];
return $self;
}
sub speak {
print "meow\n";
}
###################################
package Dog;
@ISA = qw(Animal);
sub new {
my $class = $_[0];
my $self = {};
bless $self;
$self->{'name'} = $_[1];
$self->{'color'} = $_[2];
return $self;
}
sub speak {
print "woof\n";
}
###################################
package main;
my($cat) = new Cat("Fred", "white");
my($dog) = new Dog("Max", "black");
@pets = ($cat,$dog);
foreach $pet (@pets){
$pet->speak();
$pet->printDetails();
}
- encapsulation: the implementation of printDetails() is hidden from
Cat and Dog
- inheritance: Cat and Dog inherit printDetails()
- polymorphism: $pet refers to instances of different types()
Exercise
Add your pet from the previous exercise to the Animal package.
Modules
A module is a package stored in a file by itself and named
"packagename.pm". The last executed line in a module should be
"return 1;". A package can be used in a different file by including
"use packagename;" at the beginning of the file.
Exercise
Save Animal, Cat, Dog and the additional pet
as modules by themselves. To use them you can
either include "use" statements for all four of them in the main file
or you use Cat, Dog and the other pet in the main file and Animal
in Cat, Dog and the other pet.
Try both possibilities.