An interface names a set of methods that unrelated classes can promise to have. It
lives in its own .as file, named after it, like a class. Interfaces exist
mainly for the compiler: they let code be typed by what an object can do rather than by
its class.
The declaration
interface-decl = "interface" dotted-name ["extends" dotted-name]
"{" { "function" name "(" [param { "," param }] ")" [":" type] ";" } "}"
- Only methods, and only their declarations: name, parameters and return type, ending with a semicolon instead of a body.
- All its methods are public.
private,static,var,getandsetare not allowed. - An interface that extends another includes all of its methods.
// com/example/media/IPlayable.as
interface com.example.media.IPlayable {
function play():Void;
function stop():Void;
function getPosition():Number;
}
// com/example/media/ISeekable.as
import com.example.media.IPlayable;
interface com.example.media.ISeekable extends IPlayable {
function seek(seconds:Number):Void;
}
Implementing an interface
A class lists its interfaces after implements, separated by commas, after
any extends. The compiler then requires the class, or its superclasses, to
define every method of every interface, with the same parameters and return type, and
reports any that are missing or different.
import com.example.media.ISeekable;
class com.example.media.SoundTrack implements ISeekable {
private var snd:Sound;
private var offset:Number = 0;
public function SoundTrack(target:MovieClip, linkage:String) {
snd = new Sound(target);
snd.attachSound(linkage);
}
public function play():Void { snd.start(offset); }
public function stop():Void { offset = getPosition(); snd.stop(); }
public function getPosition():Number { return snd.position / 1000; }
public function seek(seconds:Number):Void { offset = seconds; play(); }
}
ISeekable and
IPlayable.Interfaces as types
An interface name can be used as the type of a variable, parameter or result. Any object whose class implements it can be assigned, and only the interface’s methods can be called on it without a cast:
function pauseAll(list:Array):Void {
for (var i:Number = 0; i < list.length; i++) {
var item:IPlayable = IPlayable(list[i]);
if (item != null) item.stop();
}
}
null for objects that
do not implement it in Flash Player 7 and later.When the movie runs
An interface compiles to an empty function stored on _global under its
package path, and a class that implements interfaces records them. In files for Flash
Player 7 and later this record is made with the ImplementsOp action, so
instanceof and casts recognise interfaces as well as classes. Nothing
checks at run time that the methods exist; that is the compiler’s job.