Using interfaces and abstract classes can be an incredible time saver and helps modularize and decouple your code. So what’s the difference and when should you use each?
In simplest terms, abstract classes can be thought of as partial templates, where interfaces act as a set of rules that classes must abide by. Here’s a simple example of an abstract class:
Here, I’ve created an Animal class that forces implementations of a Legs property as well as a Speed() method. Anything inheriting from Animal can choose to use hasFur, but doesn’t have to.
In contrast, here is a simple interface:
In this case, anything that implements IAttackable, must implement the entire contents…no exceptions.
You really want to use abstract classes when you want to define something…or at least some parts of something. For example, if you want to define a Dog as being an animal, then you would use an abstract class. Abstract classes also provide a way of preparing for future expansion. You don’t need to use all parts of an abstract class…but you can set up components to be used in the fuutre (or not).
When you want to make sure an object has some functionality…like all dogs can walk, then you would want to have an interface. At this point you are making sure that all dogs and cats have walk functionality, but they inherit from animal (which could be an abstract class). While interfaces aren’t aimed at future expansion, you can implement 1 or many interfaces that you need.
To summarize, when determining that ‘A’ is a ‘B’…use an abstract class for ‘A’ can do ‘B’. Abstract for what an object is, interface for what the object can do.