
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Casting
|
49
Don’t confuse explicit casting with merely assigning objects of one datatype to vari-
ables of another datatype, as described earlier under “Compatible Types.” To reiter-
ate, if Basketball is a subclass of the Ball class, this assignment operation is legal:
var ball1:Ball = new Basketball( ); // Assignment without casting
And this is a safe cast (an upcast):
var ball1:Ball = Ball(new Basketball( )); // Safe upcast
In this context, an explicit upcast is unnecessary, because storing the Basketball
instance in the ball1 object automatically casts the instance to the Ball class. The
automatic cast is called an implicit upcast.
Let’s look at the converse situation, which we also discussed earlier in this chapter.
This assignment operation is illegal because you can’t assign an instance of super-
type Ball to a variable of subtype Basketball:
var ball2:Basketball = new Ball( ); // Illegal!
However, the following is legal but considered an unsafe cast (a downcast):
var ball3:Basketball = Basketball(new Ball( )); // Legal, but unsafe
In this case, an explicit downcast is necessary to prevent a type mismatch error when
storing the Ball instance in the
ball3 variable, whose type is Basketball. Further-
more, the programmer must take care not to access methods and properties of the
Basketball ...