Creating Interfaces

 <  Day Day Up  >  

Interfaces are created in much the same way as class definitions. They are defined in a text file. They are then compiled and used by any class that desires to conform to the contract. They are created in external files and follow the same accessibility rules as a class file.

To create an interface, we can use the Interface keyword, just as we would use the class keyword to create a class definition. An interface is similar to a class, with the following important differences:

  • Interfaces contain only declarations of methods , not their implementation. That is, every class that implements an interface must provide an implementation for each method declared in the interface.

  • Only public members are allowed in an interface definition. In addition, instance and class members are not permitted.

  • Get and set statements are not allowed in interface definitions.

Listing 6.2 shows how to create the Pie interface. Notice that there is no code in either of the methods, not even an empty code block { } .

Listing 6.2. Creating the Pie Interface
 interface Pie { function prepare( ); function bake( ); } 

To use the Pie interface, all the methods must have implementations . Listing 6.3 shows the Apple class implementing the Pie interface.

Listing 6.3. Apple Class Implementing the Pie Interface
 class Apple  implements  Pie{ function prepare( )  {//implement };  function bake( )  { //implement };  } 

You may have noticed that there really isn't any more code in the Apple class than in the Pie class. However, there is a begin and end block for the prepare and bake methods. This satisfies the compiler as an implementation.

So how do we use the power of the interface, you ask? Well, let's say that we have a class called Bakery . In Listing 6.4, the Bakery class has a method called bakePie that takes one argument of type Pie . Regardless of whether we are baking an apple pie or a chocolate pie, the call is the same ” bake() . This is an example of polymorphism using an interface.

Listing 6.4. Polymorphic Use of the Pie Interface
 public class Bakery {       public bakePie (item:Pie){             item.bake( ); } } 

For another example, examine Figure 6.6. In it, we have a hierarchy of different types of documents, some electronic and others that are on paper. By implementing the Printable interface at the PaperDoc class level, all descendants of the PaperDoc class will have the print() method. It's important to note that the print() method is overridden in the descendants. Even though PaperDoc satisfies the contract with the interface, the code to print is at the descendant level.

Figure 6.6. Printable interface example.

graphics/06fig06.gif

 <  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