
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
38
|
Chapter 3: Datatypes and Type Checking
What would happen if the compiler allowed the preceding assignment? At some
point later in the program, we might try to access methods and properties of the
Basketball subclass on the
ball2 instance, but those methods and properties would
not be supported (the object we stored in
ball2 is a Ball, not a Basketball!). There-
fore, the compiler prevents us from storing a Ball instance in a Basketball-typed vari-
able to prevent potential runtime errors resulting from accessing methods or
properties of the Basketball class on an instance of the Ball class.
In the following example, if the first line were allowed by the compiler, we’d get into
trouble later. The second line seems reasonable at compile time (it invokes the
inflate( ) method on what it thinks is a Basketball instance). But at runtime, the inter-
preter would attempt to invoke inflate( ) on what is in fact a Ball instance (stored in
ball2). The invocation would fail because the Ball class doesn’t define the inflate( )
method:
var ball2:Basketball = new Ball( ); // If this were allowed at compile time...
ball2.inflate( ); // this would cause a runtime error!
Make sense? If not, remember that all basketballs are balls, but not all balls are bas-
ketballs. We can treat any basketball as