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.

For example, the following code first checks if the object name someObject implements the Movable interface before calling the moveUp() method on the object.

if(Movable(someObject) != null) {
  someObject.moveUp();
}