views:

902

answers:

6

Duplicate:

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

Probably one of the most famous software developer job interview questions.

What would be your answer?

EDIT: I'm trying to find out how you would answer this in a real-life situation. Please try to formulate your answer as you would on a real job interview (be complete, but don't be too long, post no links of course).

A: 

I would say that the difference is language dependent, but that in C++ at least, abstract classes are the means by which interfaces are implemented.

anon
+1  A: 

An abstract class can have member variables, an interface cannot (or, in C++, should not).

In Java, an "Interface" is a well-defined syntactical element, while in C++ it's merely a design pattern.

DevSolar
The answer was given as a "answer right now" response. It's not exhaustive, I know, but it's what I came up with ad hoc.
DevSolar
A: 

This article should answer your question:

http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx

A: 

As far as job interviews are concerned, I've always heard that the key point is that an interface is a contract; an interface, while not implementing it itself, guarantees functionality.

+5  A: 

An interface only describes the actual signature of its methods etc. Any class implementing that interface must then provide an explicit implementation.

An abstract class can contain a partial implementation of its methods etc.

LukeH
+1  A: 

Interfaces provide definitions of methods that must be implemented by a class. The purpose of interfaces is to allow you to generalise specific functionality regardless of implementation. You may have an IDatabase interface that defines Open()/Close(). The class that implements that interface may be connecting to a MySQL database or MS Access database. Irrespective of how it accomplishes this task, the goal is still the same...Open database, close database.

Abstract classes are base classes that contain some abstract methods. They cannot be instantiated they are to be derived from. The purpose of an Abstract class is to allow you to define some generic functionality and sub-class to implement more specific functionality where appropriate.

So I suppose to summarize. You should use interfaces when the implementation of each class differs completely. Use abstract classes when you have some similar behaviour but need to implement parts differently.

Hope that helps. James.

James