Base class implementing interface

Let’s think it this way;

public interface IBreathing
{
    void Breathe();
}

//because every human breathe
public abstract class Human : IBreathing
{
    abstract void Breathe();
}

public interface IVillain
{
    void FightHumanity();
}

public interface IHero
{
    void SaveHumanity();
}

//not every human is a villain
public class HumanVillain : Human, IVillain
{
    void Breathe() {}
    void FightHumanity() {}
}

//but not every human is a hero either
public class HumanHero : Human, IHero
{
    void Breathe() {}
    void SaveHumanity() {}
}

The point is that the base class should implement interface (or inherit but only expose its definition as abstract) only if every other class that derives from it should also implement that interface. So, with basic example provided above, you’d make Human implement IBreathing only if every Human breaths (which is correct here).

But! You can’t make Human implement both IVillain and IHero because that would make us unable to distinguish later on if it’s one or another. Actually, such implementation would imply that every Human is both a villain and hero at once.

Conclusion

  1. There are no risks of base class implementing an interface, if every class deriving from it should implement that interface too.
  2. It is always better to implement an interface on the sub-class, If every class deriving from base should also implement that interface, it’s rather a must
  3. If every class deriving from base one should implement such interface, make base class inherit it. If not, make concrete class implement such interface.
FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect