Using interfaces

Interfaces are a type of class that you design to act as an outline for your components. When you write an interface, you provide only the names of public methods rather than any implementation. If, for example, you define two methods in an interface and then implement that interface, the implementing class must provide implementations of those two methods.

Interfaces in ActionScript can only declare methods; they cannot specify constants. The benefits of interfaces are that you can define a contract that all classes implementing that interface must follow. In addition, if your class implements an interface, instances of that class can also be cast to that interface.

Custom MXML components can implement interfaces just as other ActionScript classes can. To do this, you use the implements attribute. All MXML tags support this attribute.

The following code is an example of a simple interface that declares several new methods:

// The following is in a file named SuperBox.as.
interface SuperBox { 
   function selectSuperItem():String; 
   function removeSuperItem():Boolean; 
   function addSuperItem():Boolean; 
}

A class that implements the SuperBox interface uses the implements attribute to point to its interface and must provide an implementation of the new methods. The following example of a custom ComboBox component implements the SuperBox interface:

<?xml version="1.0"?>
<!-- MyComboBox.mxml -->

<mx:ComboBox xmlns:mx="http://www.macromedia.com/2003/mxml" implements="SuperBox">
   <mx:Script>
      function selectSuperItem():String {
         return "Super Item was selected";
      }
      function removeSuperItem():Boolean {
         return true;
      }
      function addSuperItem():Boolean {
         return true;
      }
   </mx:Script>
   <mx:dataProvider>
      <mx:Array>
         <mx:String>AK</mx:String>
         <mx:String>AL</mx:String>
      </mx:Array>
   </mx:dataProvider>
</mx:ComboBox>

You can implement multiple interfaces by separating them with commas as the following example shows:

<mx:ComboBox xmlns:mx="http://www.macromedia.com/2003/mxml" implements="SuperBox, SuperBorder, SuperData">

All methods declared in an interface are considered public. If you define an interface and then implement that interface but do not implement all of its methods, the MXML compiler throws an error.

Methods implemented in the custom component must have the same return type as their corresponding methods in the interface. If no return type is specified in the interface, the implementing methods can declare any return type.

Getter and setter functions work differently in interfaces. The special syntax for function get propertyName() is not supported.


Version 1.5

 

Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/flex/15/flex_docs_en/00000462.htm