So far, this design is missing a key operation, and that is the one commanding creatures to
fly to a destination within the zoo. Clearly, you cannot add a Fly method to the ZooDweller
class because not all animals can fly. You must express this contract in a different way. One
common way to model this in a class is to create a Boolean property, such as CanFly, to use as a
flag that states the ZooDweller??™s ability to fly.
Implementing Contracts with Interfaces
Interfaces provide an excellent mechanism for defining our flying contract. The following
example implements an IFly interface:
Public Interface IFly
Sub FlyTo(ByVal dest As Point)
End Interface
Public Class Bird
Inherits ZooDweller
Implements IFly
Protected Overrides Sub EatTheFood()
Console.WriteLine( "Eating some food." )
End Sub
CHAPTER 6 n INTERFACES 109
Public Sub Fly(ByVal dest As Point) Implements IFly.FlyTo
Console.WriteLine( _
"Flying to ({0}. {1}).", dest)
End Sub
End Class
Now, using the interface IFly, Bird is defined such that it derives from ZooDweller and
implements IFly.
Choosing Between Interfaces and Classes
You can implement a contract with classes or interfaces, and in the zoo example, it??™s pretty
clear where you should use an interface rather than a class to define the contract.
Pages:
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201