Card 04/ 08
Interface vs Abstract Class
"Prefer interfaces" is right often enough to mislead; one question about state settles it.
Choose between an interface and an abstract class by asking whether there is state every implementation would keep in the same way. If there is, an abstract class; if not, an interface. The usual advice to "prefer interfaces" is right often enough to be misleading, and it is not about style.
| What you are sharing | Use | Because |
|---|---|---|
| A capability, with no data behind it | Interface | A class can meet several capabilities at once |
| A fixed sequence with holes in it | Abstract class | The sequence is a final method holding the order |
| Fields every implementation keeps identically | Abstract class | Only a class can declare instance fields |
| A default behaviour most classes want | Interface with a default method | No state is needed, so no class is needed |
The cost of choosing wrongly is not symmetric, which is why the advice leans the way it does. An interface that turns out to need state can gain an abstract class beside it and nothing breaks. An abstract class that turns out to be a capability has already spent the one extends every implementing class had.
In practice the common shape is both: an interface naming the capability, and an abstract class implementing the parts everyone shares. Anything that wants the shortcut extends the class; anything that already has a parent implements the interface directly.
← → move through sections and cards