A.7 Answers for Chapter 8A.7.1 Exercise 1 (Section 8.11.1)Here's one way to do it. First define the Animal class, with a single method: use strict; Now define each subclass with a specific sound: { package Cow;The Mouse package is slightly different because of the extra quietness: { package Mouse;Now, enter the interactive part of the program: my @barnyard = ( ); This code uses a simple check, via a pattern match, to ensure that the user doesn't enter Alpaca or another unavailable animal, because doing so will crash the program. In Chapter 9, you learned about the isa method, which lets you check more simply whether something is an available animal, even allowing for the possibility that it is an animal that was added to the program after the check was written. A.7.2 Exercise 2 (Section 8.11.2)Here's one way to do it. First, create the base class of LivingCreature with a single speak method: use strict; A person is a living creature, so define the derived class here: { package Person;The Animal class comes next, making appropriate sounds, but unable to talk (except to Dr. Doolittle): { package Animal;Finally, have the person speak: Person->speak; # just hmms Notice that the main speak routine has now moved into the LivingCreature class, which means you don't need to write it again to use it in Person. In Animal, though, you need to check that to ensure an Animal won't try to speak before calling SUPER::speak.Although it's not the way the assignment was written, you can get a similar result if you choose to make Person a subclass of Animal. (In that case, LivingCreature would presumably be needed as a parent class for an eventual Plant class.) Of course, since an Animal can't speak, how can a Person? The answer is that Person::speak would have to handle its parameters, if any, before or after (or instead of) calling SUPER::speak.Which would be the better way to implement this? It all depends upon what classes you'll need in the future and how you'll use them. If you expect to add features to Animal that would be needed for Person, it makes sense for Person to inherit from Animal. If the two are nearly completely distinct, and nearly anything that a Person has in common with an Animal is common to all LivingCreatures, it's probably better to avoid the extra inheritance step. The ability to design a suitable inheritance structure is a crucial talent for any OOP programmer.In fact, you may find that after developing the code one way, you'll want to "refactor" the code a different way. This is common with OOP. However, it's very important to have enough testing in place to ensure that you don't break things while you're moving them around. |
•
Table of Contents
•
Index
•
Reviews
•
Reader Reviews
•
Errata
Learning Perl Objects, References & Modules
By
Randal L. Schwartz