168 Chapter 9: Creating Classes with ActionScript 2.0
For example, the following code declares an interface named MyInterface that contains two
methods,
method_1() and method_2(). The first method takes no parameters and has no return
type (specified as
Void). The second method declaration takes a single parameter of type String,
and specifies a return type of Boolean.
interface MyInterface {
function method_1():Void;
function method_2(param:String):Boolean;
}
Interfaces cannot contain any variable declarations or assignments. Functions declared in an
interface cannot contain curly braces. For example, the following interface won’t compile.
interface BadInterface{
// Compiler error. Variable declarations not allowed in interfaces.
var illegalVar;
// Compiler error. Function bodies not allowed in interfaces.
function illegalMethod(){
}
}
The rules for naming interfaces and storing them in packages are the same as those for classes; see
“Creating and using classes” on page 161 and “Using packages” on page 171.
Interfaces as data types
Like a class, an interface defines a new data type. Any class that implements an interface can be
considered to be of the type defined by the interface. This is useful for determining if a given
object implements a given interface. For example, consider the following interface.
interface Movable {
function moveUp();
function moveDown();
}
Now consider the class Box that implements the Movable interface.
class Box implements Movable {
var x_pos, y_pos;
function moveUp() {
// method definition
}
function moveDown() {
// method definition
}
}
Then, in another script where you create an instance of the Box class, you could declare a variable
to be of the Movable type.
var newBox:Movable = new Box();
At runtime, in Flash Player 7 and later, you can cast an expression to an interface type. 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.