Base class or Interface?

When making the decision to use a base class or interface, it may help to think of the implementation. If all the implementations are going to be similar, then you might want to group them under a base class. But if the implementations will be different, an interface might be better.

An interface is a contract, and will allow classes that don’t share the same implementation to “agree” to work together.

 

MailCarrier and SalesPerson classes could be a good example of two completely different types of business logic that might use an interface to provide a similar output. If the interface has one method called “report”, then both classes could be made to output a report in some standardized format. What’s in the report, and how it was generated could be completely different. The interface ensures that an outside class or system can be guaranteed that it will get what it expects from either class.

Consider a base class called SalesPerson, and two subclasses called UsedCarSalesPerson and NewCarSalesPerson. This is a case where subclassing makes sense because how the report is generated is likely to be the same, so the logic for generating the report can be kept in the base class, and due to inheritance both child classes can call it, or even override it in some cases to tweak the output as needed.

 

Leave a Reply

Your email address will not be published. Required fields are marked *