Card 04/ 08
All 8 cards
ComparisonDifficulty: Intermediate1 min
Interface or Abstract Class: the Question That Decides It
The advice usually given is "prefer interfaces", which is right often enough to be misleading. There is a question that settles it, and it is not about style.
Is there state that every implementation would have to keep, in the same way? If yes, an abstract class. If no, an interface.
| 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.