Learning ActionScript 2.0 in Adobe Flash |
|
|
|
| Interfaces > Creating interfaces as data types | |||
Like a class, an interface defines a new data type. You can consider any class that implements an interface to be of the type that is defined by the interface. This is useful for determining whether a given object implements a given interface. For example, consider the interface IMovable, which you create in the following example.
To create an interface as a data type:
interface IMovable {
public function moveUp():Void;
public function moveDown():Void;
}
In this document, you create a Box class that implements the IMovable interface that you created in an earlier step.
class Box implements IMovable {
public var xPos:Number;
public var yPos:Number;
public function Box() {
}
public function moveUp():Void {
trace("moving up");
// method definition
}
public function moveDown():Void {
trace("moving down");
// method definition
}
}
var newBox:Box = new Box();
This ActionScript code creates an instance of the Box class, which you declare as a variable of the Box type.
In Flash Player 7 and later, you can cast an expression to an interface type or other data type at runtime. 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 ensure that a particular object implements a certain interface. For more information on type casting, see About casting objects.
if (IMovable(newBox) != null) {
newBox.moveUp();
} else {
trace("box instance is not movable");
}
This ActionScript code checks whether the newBox instance implements the IMovable interface before you call the moveUp() method on the object.
Because the Box instance implements the IMovable interface, the Box.moveUp() method is called, and the text "moving up" appears in the Output panel.
For more information about casting, see About casting objects.
|
|
|
|