Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base class implementing interface

Tags:

c#

.net

oop

  1. What are the cons/risks of base class implementing an interface?
  2. Is it better to always implement an interface on the sub-class?
  3. 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";
        }
    }
    
like image 225
BobSwanson Avatar asked Apr 02 '16 17:04

BobSwanson


1 Answers

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:

  1. What are the cons/risks of base class implementing an interface?

    None, if every class deriving from it should implement that interface too.

  2. 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

  3. 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.

like image 70
mwilczynski Avatar answered Oct 11 '22 19:10

mwilczynski