When would you use one or the other?
public interface IFriendly
{
string GetFriendly();
}
public abstract class Person: IFriendly
{
public abstract string GetFriendly();
}
VS.
public interface IFriendly
{
string GetFriendly();
}
public abstract class Person
{
// some other stuff i would like subclasses to have
}
public abstract class Employee : Person, IFriendly
{
public string GetFriendly()
{
return "friendly";
}
}
Well, you need to think of it that 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 is a hero either
public class HumanHero : Human, IHero
{
void Breathe() {}
void SaveHumanity() {}
}
The point is that you 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.
To wrap up answers to your question:
What are the cons/risks of base class implementing an interface?
None, if every class deriving from it should implement that interface too.
Is it better to always implement an interface on the sub-class?
If every class deriving from base one should also implement that interface, it's rather a must
When would you use one or the other?
If every class deriving from base one should implement such interface, make base class inherit it. If not, make concrete class implement such interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With