How to decide between an Interface or Base Class for an new implementation?

Sakthivel picture Sakthivel · Mar 23, 2013 · Viewed 24.3k times · Source

When it comes to implementation, how should i decide to go for an base type or an Interface ? I tried to work out on few examples but i don't get the complete idea :(

Examples on how and why would be greatly appreciated..

Answer

Dan picture Dan · Mar 23, 2013

A base class, abstract or not, can contain implemented members. An interface cannot. If all of your implementations are going to perform similarly, a base class might be the way to go because all of your child classes can share the same implementations of the members on the base class. If they aren't going to share implementations, then an interface might be the way to go.

Example:

class Person
{
    string Name { get; set; }
}

class Employee : Person
{
    string Company { get; set; }
}

It makes sense for Employee to inherit from Person because the Employee class doesn't have to define a Name property because it shares the implementation.

interface IPolygon
{
    double CalculateArea()
}

class Rectangle : IPolygon
{
    double Width { get; set; }
    double Height { get; set; }

    double CalculateArea()
    {
        return this.Width * this.Height;
    }
}

class Triangle : IPolygon
{
    double Base { get; set; }
    double Height { get; set; }

    double CalculateArea()
    {
        return 0.5 * this.Base * this.Height;
    }
}

Because Rectangle and Triangle have such differing implementations of CalculateArea, it doesn't make sense for them to inherit from a base class.

If you make a base class, and find that in only contains abstract members, you may as well just use an interface.

And, as j__m states, you cannot inherit from multiple base classes, but you can implement multiple interfaces.

I usually define interfaces first, and if I find myself duplicating code in my implementations, I create a base class that implements the interface, and make my implementations inherit from it.