Part 2 of 6 · 1 min read
Interface, type and class
What an object can do, versus how it does it.
A wall socket accepts any plug of the right shape. The socket does not care whether the plug belongs to a lamp or a kettle. The socket's shape is the interface, and the appliance behind the plug is one implementation.
GoF defines the interface of an object as the set of requests it can answer, and the type of an object as that interface. One object may have several types, and objects built from different classes may share one type. The class is different: it defines how the object is implemented, its internal state and the code of its operations.
So there are two questions to ask about an object. "What can I ask it to do?" is a question about type. "How does it do it?" is a question about class. Good designs let callers care only about the first.
GoF separates two kinds of inheritance as well. Class inheritance defines one object's implementation in terms of another's. It shares code. Interface inheritance, also called subtyping, says when one object can be used in place of another. Many languages blur the two, but the distinction matters in practice, and many design patterns depend on it.
Interface
An interface is the set of requests an object can answer, written down as method names and signatures, without saying how they are carried out.
Example: PricingStrategy with one method int priceInCents(Booking booking). Any class that provides that method can be used where a PricingStrategy is expected.
Check yourself: 1. Which of type and class says how an object works inside? 2. Can two different classes share one type? 3. What does interface inheritance share, and what does class inheritance share?