A Contract for Classes

 <  Day Day Up  >  

In the preceding section, implementing the additional methods in the subclass provided a viable solution for making chocolate pies and apple pies. But what if you are a large baked-goods manufacturer? You might have one team that prepares crusts and fillings and another team that fills the crusts and bakes the pies. Yet, regardless of the filling, all crusts are filled and baked.

To guarantee consistency in pie preparation, it would be better to have a common nomenclature for these processes. The team could agree on using the nomenclature prepare() and bake() . Depending on the filling, the bake time might be longer and the crust treated differently, but in both cases, the pie is prepared and baked. If we say that all classes that can become pies will have methods called prepare() and bake() , we have established a relationship between classes that can become pies and a set of predetermined methods and attributes for the "pie-able" classes. This is often referred to as a contract.

In object-oriented programming (OOP), we can establish and enforce a contract using interfaces. We establish the contract using the implements keyword in the class definition. The compiler enforces the contract by requiring that the class contain an implementation for each method in the interface. In Figure 6.5, we can see that a contract has been established between Apples and Pie and between Chocolate and Pie . Both Apples and Chocolate have contracted with the same interface to provide method implementation for the Pie methods.

Figure 6.5. Pie interface relationship.

graphics/06fig05.gif

The contract exists between the Apples class and the Pie interface and the Chocolate class and the Pie interface. The contract ensures that for any class to become a pie or be called a pie, it must have certain methods. The interface itself has no implementation. The interface Pie is merely a specification, an empty set of methods. The implementation exists in the class, such as Apples or Chocolate , that implements the interface. In Figure 6.5, this is illustrated with the code block { } for the Pie class methods in the implementing class.

 <  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