O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Interfaces and Multidatatype Classes

In the preceding section, we created the LogRecipient datatype by creating a LogRecipient class. That approach forces every Logger message-recipient to be an instance of either LogRecipient or a LogRecipient subclass. To loosen that restriction, we can define the LogRecipient datatype by creating a LogRecipient interface rather than a LogRecipient class. That way, instances of any class that formally agrees to provide an implementation for update( ) can register for log messages. Let's see how this works.

Syntactically, an interface is simply a list of methods. For example, the following code creates an interface named LogRecipient that contains a single method, update( ). (Notice that, like classes, interfaces can be defined as either public or internal.)

public interface LogRecipient {
  function update(msg:String):void;
}

Once an interface has been defined, any number of classes can use the keyword implements to enter into an agreement with it, promising to define the methods it contains. Once such a promise has been made, the class's instances are considered members of both the class's datatype and the interface's datatype.

For example, to indicate that the LogUI class agrees to define the method update( ) (defined by the LogRecipient interface), we use the following code:

class LogUI extends Sprite implements LogRecipient {
  public function update (msg:String):void {
    // Display status message on screen, code not shown...
  }
}

Instead of extending ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required