8.2 Interfaces and Multidatatype Classes

 <  Day Day Up  >  

Earlier, we created the OrderListener datatype by defining an OrderListener class. That approach forces every OrderProcessor event consumer to be an instance of either OrderListener or an OrderListener subclass. To loosen that restriction, we can create the OrderListener datatype by defining an OrderListener interface rather than an OrderListener class. That way, any class can agree to provide an implementation for OrderListener while still inheriting from any other class. Let's see how this works.

Syntactically, an interface is simply a list of methods . For example, the following code creates an interface named OrderListener that contains a single method, onOrderError( ) :

  interface  OrderListener {   function onOrderError( ); } 

Classes use the implements keyword to enter into an agreement with an interface, promising to define the methods it contains. For example, to indicate that the OrderUI class agrees to define the method onOrderError( ) (defined by the OrderListener interface), we use this code (note the portion in bold):

 class OrderUI extends MovieClip  implements OrderListener  {   public function onOrderError ( ) {     // Display problem report on screen, not shown...   } } 

Instead of extending the OrderListener class, the OrderUI class extends MovieClip and implements the OrderListener interface. Because OrderUI implements OrderListener , it can be used anywhere the OrderListener datatype is required. Instances of OrderUI now belong to two datatypes: OrderUI and OrderListener . Thus, despite the fact that OrderUI extends MovieClip , OrderUI instances still belong to the OrderListener type and can be passed safely to OrderProcessor.addListener( ) . (Wow, Ron, that's amazing! It's a pasta maker and a juicer!)

If OrderUI didn't define a method named onOrderError( ) , the compiler would generate the following error:

 The class must implement method 'onOrderError' from interface 'OrderListener'. 

Compiler errors are the key to the entire interface system. They guarantee that a class lives up to its implementation promises, which allows external code to use it with the confidence that it will behave as required. That confidence is particularly important when designing an application that will be extended by another developer or used by third parties.

Now that we have a general idea of what interfaces are and how they're used, let's get down to some nitty-gritty syntax details.

The hypothetical order application just discussed is one example of the delegation event model , which is covered in detail in Chapter 19.


 <  Day Day Up  >  


Essential ActionScript 2.0
Essential ActionScript 2.0
ISBN: 0596006527
EAN: 2147483647
Year: 2004
Pages: 177
Authors: Colin Moock

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net