Interfaces: Contract-Based Design and Multiple Contracts
What you'll learn: When to use interfaces to define contracts, especially when a class needs to fulfill multiple roles or behaviors.
The Contract Metaphor in Action
Think of interfaces as job descriptions rather than family trees. While abstract classes say "you ARE this type of thing," interfaces say "you CAN DO these things." This distinction becomes powerful when a class needs to wear multiple hats.
When to Choose Interfaces
Use interfaces to define contracts when:
1. Multiple unrelated classes share a capability
A Drawable interface can be implemented by Circle, Text, and Button—all very different classes that happen to need drawing behavior.
2. A class must fulfill multiple roles
A SmartPhone class might implement Camera, MusicPlayer, and WebBrowser. These are distinct contracts describing separate capabilities. With abstract classes, you're stuck with single inheritance—you can only extend one parent. Interfaces let you implement as many contracts as needed.
3. You're defining pure behavior without shared state
If your contract doesn't need instance variables or common implementation logic, an interface is cleaner than an abstract class. You're specifying WHAT must be done, not HOW.
4. You want maximum flexibility
Interfaces allow unrelated classes from different hierarchies to share contracts. A Comparable interface works for String, Integer, and your custom Product class—none of which share an inheritance relationship.
The Design Decision
Ask yourself: "Does this class IS-A something (inheritance) or CAN-DO something (interface)?" A Dog IS-AN Animal (abstract class), but it CAN-MAKE-SOUND (interface Audible), CAN-BE-TRAINED (interface Trainable), and CAN-BE-TRACKED (interface Trackable).
Key Takeaway: Use interfaces to define contracts when you need to describe capabilities or roles that multiple unrelated classes can fulfill, especially when a single class must satisfy several independent contracts simultaneously.