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

Datatypes in the Virtual Zoo

Now that we've learned all about datatypes, let's add type annotations to our virtual zoo program. Example 8-1 shows the updated code for the VirtualZoo class, the program's main class.

Example 8-1. The VirtualZoo class

package {
  import flash.display.Sprite;
  import zoo.*;

  public class VirtualZoo extends Sprite {
    private var pet:VirtualPet;

    public function VirtualZoo () {
      pet = new VirtualPet("Stan");
      pet.eat(new Apple());
      pet.eat(new Sushi());
    }
  }
}

Example 8-2 shows the code for the VirtualPet class, whose instances represent pets in the zoo. Notice the cast operation in the eat( ) method, discussed in the earlier section "Upcasting and Downcasting."

Example 8-2. The VirtualPet class

package zoo { import flash.utils.setInterval; import flash.utils.clearInterval; public class VirtualPet { private static var maxNameLength:int = 20; private static var maxCalories:int = 2000; private static var caloriesPerSecond:int = 100; private var petName:String; private var currentCalories:int = VirtualPet.maxCalories/2; private var digestIntervalID:int; public function VirtualPet (name:String):void { setName(name); digestIntervalID = setInterval(digest, 1000); } public function eat (foodItem:Food):void { if (currentCalories == 0) { trace(getName() + " is dead. You can't feed it."); return; } if (foodItem is Apple) { // Note the cast to Apple if (Apple(foodItem).hasWorm()) { trace("The " + foodItem.getName() + " had a worm. " + getName() + " didn't eat it."); return; } ...

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