User Guide

Instance and class members 263
In another script, such as the following code, where you create an instance of the Box class, you
could declare a variable to be of the Movable type:
import Box;
var newBox:Movable = new Box();
At runtime, in Flash Player 7 and later, you can cast an expression to an interface type. Unlike
Java interfaces, ActionScript interfaces exist at runtime, which allows type casting. If the
expression is an object that implements the interface or has a superclass that implements the
interface, the object is returned. Otherwise,
null is returned. This is useful if you want to make
sure that a particular object implements a certain interface.
For example, the following code first checks if the object name
newBox implements the Movable
interface before calling the
moveUp() method on the object:
if (Movable(newBox) != null) {
newBox.moveUp();
}
For more information about casting, see “Casting objects” on page 42.
Instance and class members
In object-oriented programming, members (properties or methods) of a class can be
instance members or class members. Instance members are created for each instance of the class;
they are defined to the prototype of the class when they are declared outside of its constructor
function. In contrast, class members are created once per class. (Class members are also known as
static members.)
To invoke an instance method or access an instance property, you reference an instance of the
class. In the following example,
picture_01, an instance of a custom class, invokes the
showInfo() method:
picture_01.showInfo();
Class (static) members, however, are assigned to the class, not to any instance of the class. To
invoke a class method or access a class property, you reference the class name, rather than a
specific instance of the class, as shown in the following example:
ClassName.classMember;
For example, the ActionScript Math class consists only of static methods and properties. To call
any of its methods, you dont create an instance of the Math class. Instead, you simply call the
methods on the Math class itself. The following code calls the
sqrt() method of the Math class:
var square_root:Number = Math.sqrt(4);
Creating class members
All the members (methods and properties) discussed so far in this chapter are of a type called
instance members. For each instance member, theres a unique copy of that member in every
instance of the class. For example, the
age member variable of the Person class is an instance
member, because each Person has a different age.