Why Use Interfaces?

 <  Day Day Up  >  

There are two benefits to using an interface. The first is that there are consistent method and attribute names for all classes that have a contract with the interface. The second, and more important, benefit is that any class with a relationship to the interface can be referenced by the interface datatype.

Because an interface is much like a class, it can be used as an object datatype. Using an interface is much like using a superclass and inheritance; the relationship enables us to use the interface datatype to reference the object. This is often considered a side door to multiple inheritance.

As shown in Figure 6.5, our apple can be called a fruit or it can be called a pie. If we call it a fruit, we can use the method grow() . If we call it a pie, we can use the methods prepare() and bake() .

In Listing 6.1, the preparePie() method takes an argument of type Pie . preparePie() will take any object datatype that has implemented the Pie interface. The actual code that is executed is determined by the datatype of the object at runtime. If it is a chocolate pie, the methods prepare() and bake() will be called on the chocolate object instance; if it is an apple pie, the methods prepare() and bake() will be called on the apple object instance.

Listing 6.1. Using the Pie Datatype
 var apples =  new Apples( ); var chocolate = new Chocolate( ); preparePie(apples); preparePie(chocolate); function preparePie(thePie:Pie){      //this method doesn't have to know       thePie.prepare( );             //whether it is a chocolate pie or an apple pie.       thePie.bake( ); } 
 <  Day Day Up  >  


Object-Oriented Programming with ActionScript 2.0
Object-Oriented Programming with ActionScript 2.0
ISBN: 0735713804
EAN: 2147483647
Year: 2004
Pages: 162

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