Using Inheritance in the Virtual Zoo Program

In our virtual zoo program, we'll use inheritance in two different ways. First, we'll use it to define types of food for our pets to eat—replacing our earlier approach of adding raw calories to pets through the eat( ) method. Second, we'll use inheritance to make our application's main class, VirtualZoo, displayable on screen.

Creating Types of Pet Food

Until now, our implementation of eating in the virtual zoo program has been overly simplistic. To make a pet eat, we simply invoke eat( ) on the desired VirtualPet object and specify an arbitrary number of calories for the pet to eat. To improve the realism of our simulation, let's add types of food to the zoo program.

To keep things simple, we'll allow our pet to eat only two types of food: sushi and apples. We'll represent sushi with a new class, Sushi, and apples with a new class, Apple. Because the Sushi and Apple classes both conceptually represent food, they have nearly identical functionality. Hence, in our application, we'll implement the functionality needed by both Sushi and Apple in a single superclass, Food. The Sushi and Apple classes will extend Food and, through inheritance, adopt its features.

The Food class defines four simple methods for retrieving and modifying the name and calorie value of a given piece of food. Here's the code:

package zoo { public class Food { private var calories; private var name; public function Food (initialCalories) { setCalories(initialCalories); ...

Get Essential ActionScript 3.0 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.