Interfaces VS. Abstract Classes

Interface vs Abstract Class (general OO)

While your question indicates it's for "general OO", it really seems to be focusing on .NET use of these terms.

In .NET (similar for Java):

  • interfaces can have no state or implementation
  • a class that implements an interface must provide an implementation of all the methods of that interface
  • abstract classes may contain state (data members) and/or implementation (methods)
  • abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itself)
  • interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).

As general OO terms, the differences are not necessarily well-defined. For example, there are C++ programmers who may hold similar rigid definitions (interfaces are a strict subset of abstract classes that cannot contain implementation), while some may say that an abstract class with some default implementations is still an interface or that a non-abstract class can still define an interface.

Indeed, there is a C++ idiom called the Non-Virtual Interface (NVI) where the public methods are non-virtual methods that 'thunk' to private virtual methods:

  • http://www.gotw.ca/publications/mill18.htm
  • http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface

What's the difference between an abstract class and an interface?

There are technical differences between Abstract Classes and Interfaces, that being an Abstract Class can contain implementation of methods, fields, constructors, etc, while an Interface only contains method and property prototypes. A class can implement multiple interfaces, but it can only inherit one class (abstract or otherwise).

However, in my opinion, the most important difference between Interfaces and Abstract Classes is the semantic difference.

An Interface defines what something can do (how it behaves), and an Abstract Class defines what something is.

Take for example IEnumerable, the semantic meaning behind this is that anything that implements IEnumerable is enumerable, it doesn't mean that it's an enumeration, but that it can behave like one (can be enumerated).

Contrast that with a washing machine example, anything that inherits it is a type of washing machine. Anything that inherits it would be a type of washing machine, a top loader, or side loader, etc.

Instead, if you had an interface called ICanWash, which could contain a method called Wash. You could have various things implement ICanWash, be it a Person, an abstract washing machine class, etc, where the actual implementation does not matter, just you need to know that the behavior is that it can wash things.

In summary, classes define what something is, interfaces define what something can do.

Abstract Class vs Interface in C++

I assume that with interface you mean a C++ class with only pure virtual methods (i.e. without any code), instead with abstract class you mean a C++ class with virtual methods that can be overridden, and some code, but at least one pure virtual method that makes the class not instantiable.
e.g.:

class MyInterface
{
public:
// Empty virtual destructor for proper cleanup
virtual ~MyInterface() {}

virtual void Method1() = 0;
virtual void Method2() = 0;
};

class MyAbstractClass
{
public:
virtual ~MyAbstractClass();

virtual void Method1();
virtual void Method2();
void Method3();

virtual void Method4() = 0; // make MyAbstractClass not instantiable
};

In Windows programming, interfaces are fundamental in COM. In fact, a COM component exports only interfaces (i.e. pointers to v-tables, i.e. pointers to set of function pointers). This helps defining an ABI (Application Binary Interface) that makes it possible to e.g. build a COM component in C++ and use it in Visual Basic, or build a COM component in C and use it in C++, or build a COM component with Visual C++ version X and use it with Visual C++ version Y.
In other words, with interfaces you have high decoupling between client code and server code.

Moreover, when you want to build DLL's with a C++ object-oriented interface (instead of pure C DLL's), as described in this article, it's better to export interfaces (the "mature approach") instead of C++ classes (this is basically what COM does, but without the burden of COM infrastructure).

I'd use an interface if I want to define a set of rules using which a component can be programmed, without specifying a concrete particular behavior. Classes that implement this interface will provide some concrete behavior themselves.

Instead, I'd use an abstract class when I want to provide some default infrastructure code and behavior, and make it possible to client code to derive from this abstract class, overriding the pure virtual methods with some custom code, and complete this behavior with custom code.
Think for example of an infrastructure for an OpenGL application.
You can define an abstract class that initializes OpenGL, sets up the window environment, etc. and then you can derive from this class and implement custom code for e.g. the rendering process and handling user input:

// Abstract class for an OpenGL app.
// Creates rendering window, initializes OpenGL;
// client code must derive from it
// and implement rendering and user input.
class OpenGLApp
{
public:
OpenGLApp();
virtual ~OpenGLApp();
...

// Run the app
void Run();

// <---- This behavior must be implemented by the client ---->

// Rendering
virtual void Render() = 0;

// Handle user input
// (returns false to quit, true to continue looping)
virtual bool HandleInput() = 0;

// <--------------------------------------------------------->

private:
//
// Some infrastructure code
//
...
void CreateRenderingWindow();
void CreateOpenGLContext();
void SwapBuffers();
};

class MyOpenGLDemo : public OpenGLApp
{
public:
MyOpenGLDemo();
virtual ~MyOpenGLDemo();

// Rendering
virtual void Render(); // implements rendering code

// Handle user input
virtual bool HandleInput(); // implements user input handling

// ... some other stuff
};

What is the difference between an interface and abstract class?

Interfaces

An interface is a contract: The person writing the interface says, "hey, I accept things looking that way", and the person using the interface says "OK, the class I write looks that way".

An interface is an empty shell. There are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern.

For example (pseudo code):

// I say all motor vehicles should look like this:
interface MotorVehicle
{
void run();

int getFuel();
}

// My team mate complies and writes vehicle looking that way
class Car implements MotorVehicle
{

int fuel;

void run()
{
print("Wrroooooooom");
}

int getFuel()
{
return this.fuel;
}
}

Implementing an interface consumes very little CPU, because it's not a class, just a bunch of names, and therefore there isn't any expensive look-up to do. It's great when it matters, such as in embedded devices.


Abstract classes

Abstract classes, unlike interfaces, are classes. They are more expensive to use, because there is a look-up to do when you inherit from them.

Abstract classes look a lot like interfaces, but they have something more: You can define a behavior for them. It's more about a person saying, "these classes should look like that, and they have that in common, so fill in the blanks!".

For example:

// I say all motor vehicles should look like this:
abstract class MotorVehicle
{

int fuel;

// They ALL have fuel, so lets implement this for everybody.
int getFuel()
{
return this.fuel;
}

// That can be very different, force them to provide their
// own implementation.
abstract void run();
}

// My teammate complies and writes vehicle looking that way
class Car extends MotorVehicle
{
void run()
{
print("Wrroooooooom");
}
}

Implementation

While abstract classes and interfaces are supposed to be different concepts, the implementations make that statement sometimes untrue. Sometimes, they are not even what you think they are.

In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes with no method declared.

In Python, abstract classes are more a programming trick you can get from the ABC module and is actually using metaclasses, and therefore classes. And interfaces are more related to duck typing in this language and it's a mix between conventions and special methods that call descriptors (the __method__ methods).

As usual with programming, there is theory, practice, and practice in another language :-)

When to use an interface instead of an abstract class and vice versa?

I wrote an article about that:

Abstract classes and interfaces

Summarizing:

When we talk about abstract classes we are defining characteristics of an object type; specifying what an object is.

When we talk about an interface and define capabilities that we promise to provide, we are talking about establishing a contract about what the object can do.



Related Topics



Leave a reply



Submit