Card 04/ 08

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.

Which of the two fits, by what is being shared
What you are sharingUseBecause
A capability, with no data behind itInterfaceA class can meet several capabilities at once
A fixed sequence with holes in itAbstract classThe sequence is a final method holding the order
Fields every implementation keeps identicallyAbstract classOnly a class can declare instance fields
A default behaviour most classes wantInterface with a default methodNo 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.