O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required