Card 04/ 08

ComparisonDifficulty: Intermediate1 min

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.

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.