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

Casting

In the preceding section, we learned that in strict mode, the compiler reports reference errors at compiletime. To detect reference errors, the compiler relies on type annotations. For example, suppose the compiler encounters a method reference made through a typed variable. To determine whether the reference is valid, the compiler checks for the method's definition in the class or interface specified by the variable's type annotation. If the class or interface does not define the referenced method, the compiler generates a reference error.

Tip

Notice that it is the class or interface specified by the type annotation—not the actual class of the value—that determines whether the reference error occurs.

Consider the following code, in which the hasWorm( ) method is invoked on an Apple object through a variable of type Food:

var meal:Food = new Apple();
meal.hasWorm();  // Attempt to call hasWorm() on meal

When compiling the preceding code in strict mode, the compiler must decide whether the hasWorm( ) method can be invoked on meal's value. To do so, the compiler checks to see whether the Food class (i.e., the class specified by meal's type annotation) defines hasWorm( ). The Food class defines no such method, so the compiler generates a reference error. Of course, by looking at the code, we know that meal's value (an Apple object) supports the hasWorm( ) method. But compiler doesn't. ActionScript must wait until runtime to learn that the variable's value is actually an Apple object. ...

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