Chapter 14. InterfacesThere are times when a designer does not want to create a new type. Rather, the designer wants to describe a set of behaviors that any number of types might implement. For example, a designer might want to describe what it means to be storable (i.e., capable of being written to disk) or printable. Such a description is called an interface. An interface is a contract; the designer of the interface says "if you want to provide this capability, you must implement these methods." The implementer of the interface agrees to the contract and implements the required methods. When a class implements an interface, it tells any potential client "I guarantee I'll support the methods, properties, events, and indexers of the named interface." The interface details the return type from each method and the parameters to the methods.
When specifying interfaces, it is easy to get confused about who is responsible for what. There are three concepts to keep clear:
Interfaces are a critical addition to any framework, and they are used extensively throughout .NET. For example, the collection classes (stacks, queues, hashtables) are defined, in large measure, by the interfaces they implement. (The collection classes are explained in detail in Chapter 16.) In this chapter, you will learn how to create, implement, and use interfaces. You'll learn how one class can implement multiple interfaces, and you will also learn how to make new interfaces by combining existing interfaces or by extending (deriving from) an existing interface. Finally, you will learn how to test whether a class has implemented an interface. |