What Interfaces Are
An interface is a contract. When you design an interface, you’re saying, “If you want to provide this capability, you must implement these methods, provide these properties and indexers, and support these events.” The implementer of the interface agrees to the contract and implements the required elements.
Tip
You saw methods and properties in Chapter 8. We’ll discuss indexers in Chapter 14 and events in Chapter 17. We promise you don’t need to know about them for this chapter.
When you specify interfaces, it is easy to get confused about who is responsible for what. There are three concepts to keep clear:
- The interface
This is the contract. By convention, interface names begin with a capital I, so your interface might have a name such as
IPrintable. TheIPrintableinterface might require, among other things, aPrint( )method. This states that any class that wants to implementIPrintablemust implement aPrint( )method, but it does not specify how that method works internally. That is up to the designer of the implementing class.- The implementing class
This is the class that agrees to the contract described by the interface. For example,
Documentmight be a class that implementsIPrintableand thus implements thePrint( )method in whatever way the designer of theDocumentclass thinks is appropriate.- The client class
The client calls methods on the implementing class. For example, you might have an
Editorclass that has an array ofIPrintableobjects (every object ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access