Chapter 15. Objects with Data
Using the simple syntax introduced in Chapter 13, we have class methods, (multiple) inheritance, overriding, and extending. Weâve been able to factor out common code and to provide a way to reuse implementations with variations. This is at the core of what objects provide, but objects also provide instance data, which we cover in this chapter.
A Horse Is a Horse, of Course of CourseâOr Is It?
We look at the code we used for the Animal
classes and Horse
classes. The Animal
class provides the general speak
subroutine:
package
Animal
;
sub
speak
{
my
$class
=
shift
;
"a $class goes "
,
$class
â
>
sound
,
"!\n"
}
The Horse
class inherits from
Animal
but provides its specific
sound
routine:
package
Horse
;
use
parent
qw(Animal)
;
sub
sound
{
'neigh'
}
This lets us invoke Horseâ>speak
to ripple upward to Animal::speak
, calling back to Horse::sound
to get the specific sound, and
gives us this output:
a
Horse
goes
neigh
!
But all Horse
objects would have
to be absolutely identical. If we add a method, all horses automatically
share it. Thatâs great for making identical horses, but how do we capture
the properties of an individual horse? For example, suppose we want to
give our horse a name. Thereâs got to be a way to keep its name separate
from those of other horses.
We can do so by establishing an instance. An instance is generally created by a class, much like a car is created by a car factory. An instance will have associated properties, called instance ...
Get Intermediate Perl, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.