
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
48
|
Chapter 3: Datatypes and Type Checking
Note that you can’t just cast ship to a new class, such as Fighter, and then use it as if
it belongs to the new class, because casting won’t permanently change
ship’s
datatype. This won’t work:
} else if (ship instanceof Fighter) {
ship = Fighter(ship); // Doesn't change ship's datatype
ship.callReinforcements( ); // Still generates compile-time error
ship.fire( ); // Still generates compile-time error
}
However, if you need to call many methods on an object, you can create a new vari-
able, such as fightShip, and use it to store the value of ship cast to the Fighter class.
For example:
} else if (ship instanceof Fighter) {
fightShip:Fighter = Fighter(ship); // Cast to Fighter
fightShip.callReinforcements( ); // Now this works
fightShip.fire( ); // And so does this
}
Casting Terminology
Before we continue, let’s pause to consider some common casting terminology. Cast-
ing an object to one of its supertypes is known as an upcast. Normally a supertype is a
superclass, but it could also be a superinterface (see Chapter 8). For example, if
Basketball is a subclass of Ball, then the following operation is considered an upcast:
var bball:Basketball = new Basketball( );
var genericBall:Ball = Ball(bball); // Upcast of bball
Conversely, casting an object ...