When should I use an interface and when should I use a base class?
You should use interface if
abstract
methods and don't have non-abstract methodsnon abstract
methods (except for Java 8 language, where interface methods provides default implementation)interface
more usable compared to abstract
classes.Have a look at this SE question for more details.
Should it always be an interface if I don't want to actually define a base implementation of the methods?
Yes. It's better and cleaner. Even if you have a base class with some abstract methods, let's base class extends abstract
methods through interface. You can change interface in future without changing the base class.
Example in java:
abstract class PetBase implements IPet {
// Add all abstract methods in IPet interface and keep base class clean.
Base class will contain only non abstract methods and static methods.
}
If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don't understand which to use for a generic Pet.
I prefer to have base class implement the interface.
abstract class PetBase implements IPet {
// Add all abstract methods in IPet
}
/*If ISheds,IBarks is common for Pets, your PetBase can implement ISheds,IBarks.
Respective implementations of PetBase can change the behaviour in their concrete classes*/
abstract class PetBase implements IPet,ISheds,IBarks {
// Add all abstract methods in respective interfaces
}
Advantages:
If I want to add one more abstract method in existing interfaces, I simple change interface without touching the abstract base class. If I want to change the contract, I will change interface & implementation classes without touching base class.
You can provide immutability to base class through interface. Have a look at this article
Refer to this related SE question for more details:
How should I have explained the difference between an Interface and an Abstract class?