< 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:
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 Interfaceinterface 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 Interfaceclass 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 Interfacepublic 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.
|
< Day Day Up > |