views:

3505

answers:

13

This may be a generic OOP question. I wanted to do generic comparison between an interface and an abstract class on the basis of their usage. When would one want to use and interface and when would on want to use an abstract class?

A: 

Use an abstract class if you want to provide some basic implementations.

Sebastian Sedlak
Thanks Sebastian. But What if I don't need to have a basic implementation? Wont an abstract class and interface be the same then if this is the only difference between them? Why is there a difference?
Chirantan
Because some languages don't have interfaces - C++.
jmucchiello
A: 

in java you can inherit from one (abstract) class to "provide" functionality and you can implement many interfaces to "ensure" functionality

Peter Miehle
lil' hint: if you want to inherit from an abstract class and an interface, be sure, that the abstract class implements the interface
Andreas Niedermair
+2  A: 

An abstract class can have shared state or functionality. An interface is only a promise to provide the state or functionality. A good abstract class will reduce the amount of code that has to be rewritten because it's functionality or state can be shared. The interface has no defined information to be shared

Alex
A: 

This can be a very difficult call to make...

One pointer I can give: An object can implement many interfaces, whilst an object can only inherit one base class( in a modern OO language like c#, I know C++ has multiple inheritance - but isn't that frowned upon?)

Adrian
Multiple inheritence allows for Mixin's to be implemented seemlessly, well written Mixin's are a breeze to work with but very hard to come by and difficult to write without falling short somewhere. Mixin's are pretty cool as a whole though IMO.
Martijn Laarman
oh great, and you marked my answer down because of this...?
Adrian
Actually i didn't, multiple inheritence is indeed a sure debate sparker between us geeks i see absolutely no reason to downvote. In fact i upvoted your answer.
Martijn Laarman
The only point i tried to make is that ways to Mixin in languages with Single Inheritence is possible too (C#, PHP, javascript) but trough hacky behaviour or tacky syntax. I love Mixin's when they work but i'm still undecisive on wheter to from upon multiple inheritence or not.
Martijn Laarman
A: 

An abstract class can have implementations.

An interface doesn't have implementations, it simply defines a kind of contract.

There can also be some language-dependent differences: for example C# does not have multiple inheritance, but multiple interfaces can be implemented in a class.

Gerrie Schenck
When you say, "a kind of contract", do you mean like in web services?
Chirantan
Technically speaking, web services do not work with interfaces.With contract I mean the user of an object knows which methods are present on that object. For example an interface IMouse will have a Move method, and a left and right mouse button event.
Gerrie Schenck
A: 

The answers vary between languages. For example, in Java a class can implement (inherit from) multiple interfaces but only inherit from one abstract class. So interfaces give you more flexibility. But this is not true in C++.

Nick Fortescue
+1  A: 

Purely on the basis of inheritance, you would use an Abstract where you're defining clearly descendant, abstract relationships (i.e. animal->cat) and/or require inheritance of virtual or non-public properties, especially shared state (which Interfaces cannot support).

You should try and favour composition (via dependency injection) over inheritance where you can though, and note that Interfaces being contracts support unit-testing, separation of concerns and (language varying) multiple inheritance in a way Abstracts cannot.

annakata
+17  A: 

I wrote an article about that:

http://www.thecoldsun.com/en/content/01-2009/abstract-classes-and-interfaces

Summarizing: When we talk about abstract classes we are defining characteristics of an object type, specifying what an object is but in the case of an interface we define a capability and we bond to provide that capability, we are talking about establishing a contract about what the object can do.

Jorge Córdoba
I down vote because when type A implements an abstract class or an interface B, the relation is always "A is a B".
Nicolas Dorier
Characteristics of an object type are in data members ? If yes, then even interfaces can have data members.What contract are you talking about ? Cant the abstract class define what the object can do ?Load of s**t to me.
WarDoGG
too bad this article link is a dead one
Sev
Yep, I have to renew the domain but the hosting company is messing up ... it should be back up in a couple of days.
Jorge Córdoba
+15  A: 

Personally, I almost never have the need to write abstract classes.

Most times I see abstract classes being (mis)used, it's because the author of the abstract class is using the "Template method" pattern.

The problem with "Template method" is that it's nearly always somewhat re-entrant - the "derived" class knows about not just the "abstract" method of its base class that it is implementing, but also about the public methods of the base class, even though most times it does not need to call them.

(Overly simplified) example:

abstract class QuickSorter
{
    public void Sort(object[] items)
    {
        // implementation code that somewhere along the way calls:
        bool less = compare(x,y);
        // ... more implementation code
    }
    abstract bool compare(object lhs, object rhs);
}

So here, the author of this class has written a generic algorithm and intends for people to use it by "specializing" it by providing their own "hooks" - in this case, a "compare" method.

So the intended usage is something like this:

class NameSorter : QuickSorter
{
    public bool compare(object lhs, object rhs)
    {
        // etc.
    }
}

The problem with this is that you've unduly coupled together two concepts:

  1. A way of comparing two items (what item should go first)
  2. A method of sorting items (i.e. quicksort vs merge sort etc.)

In the above code, theoretically, the author of the "compare" method can re-entrantly call back into the superclass "Sort" method... even though in practise they will never want or need to do this.

The price you pay for this unneeded coupling is that it's hard to change the superclass, and in most OO languages, impossible to change it at runtime.

The alternative method is to use the "Strategy" design pattern instead:

interface IComparator
{
    bool compare(object lhs, object rhs);
}

class QuickSorter
{
    private readonly IComparator comparator;
    public QuickSorter(IComparator comparator)
    {
        this.comparator = comparator;
    }

    public void Sort(object[] items)
    {
        // usual code but call comparator.Compare();
    }
}

class NameComparator : IComparator
{
    bool compare(object lhs, object rhs)
    {
        // same code as before;
    }
}

So notice now: All we have are interfaces, and concrete implementations of those interfaces. In practise, you don't really need anything else to do a high level OO design.

To "hide" the fact that we've implemented "sorting of names" by using a "QuickSort" class and a "NameComparator", we might still write a factory method somewhere:

ISorter CreateNameSorter()
{
    return new QuickSorter(new NameComparator());
}

Any time you have an abstract class you can do this... even when there is a natural re-entrant relationship between the base and derived class, it usually pays to make them explicit.

One final thought: All we've done above is "compose" a "NameSorting" function by using a "QuickSort" function and a "NameComparison" function... in a functional programming language, this style of programming becomes even more natural, with less code.

Paul Hollingsworth
Just because you can use Abstract classes or Template Method pattern doesn't mean you need to avoid them. Strategy Pattern is a different pattern for a different situation as in this example, but there are lots of examples where a template pattern is mucho more suitable than Strategy.
Jorge Córdoba
Well, in my experience I never run into them (situations where template method is preferable)... or rarely anyway. And that's all "abstract" is - language support for the "template method" design pattern.
Paul Hollingsworth
Ok, I used it once for an expert system where the process was something like, get 1. FillTheParameters, 2. Make The Vector Product between them, 3. For Each Pair compute result, 4. Join the results, where steps 1 and 3 where delegated and 2 and 4 implemented in the base class.
Jorge Córdoba
Not just your example but most of the others smacks of the reason that many people complain that OO systems get too complicated. Yes, you gained some benefits by using the interface approach but the abstract class approach is far, far easier to comprehend and use.
Dunk
I find almost any use of abstract classes harder to understand. Thinking in terms of boxes that communicate with each other instead of inheritance relationships is easier (for me)... But I also agree that current OO languages force too much boilerplate... Functional will be the way to go over OO
Paul Hollingsworth
Wish I could vote this one up more then once.
Matt Briggs
+1  A: 

When to do what is a very simple thing if you have the concept clear in your mind.

Abstract classes can be Derived whereas Interfaces can be Implemented. There is some difference between the two. When you derive an Abstract class, the relationship between the derived class and the base class is 'is a' relationship. e.g., a Dog is an Animal, a Sheep is an Animal which means that a Derived class is inheriting some properties from the base class.

Whereas for implementation of interfaces, the relationship is "can be". e.g., a Dog can be a spy dog. A dog can be a circus dog. A dog can be a race dog. Which means that you implement certain methods to acquire something.

I hope I am clear.

Aamir
A: 

One interesting location where interfaces fare better than abstract classes is when you need to add extra functionality to a group of (related or unrelated) objects. If you cannot give them a base abstract class (e.g., they are sealed or already have a parent), you can give them a dummy (empty) interface instead, and then simply write extension methods for that interface.

Dmitri Nesteruk
+1  A: 

I wrote an article of when to use an abstract class and when to use an interface. There is a lot more of a difference between them other than "one IS-A... and one CAN-DO...". To me, those are canned answers. I mention a few reasons when to use either of them. Hope it helps.

http://codeofdoom.com/wordpress/2009/02/12/learn-this-when-to-use-an-abstract-class-and-an-interface/

+3  A: 

OK, having just "grokked" this myself - here it is in layman's terms (feel free to correct me if I am wrong) - I know this topic is oooooold, but someone else might stumble across it one day...

Abstract classes allow you to create a blueprint, and allow you to additionally CONSTRUCT (implement) properties and methods you want ALL its descendants to possess.

An interface on the other hand only allows you to declare that you want properties and/or methods with a given name to exist in all descendants - regardless of implementation. Also, a class can implement MANY interfaces, but can only extend ONE Abstract class.

Even though both get "extended", they serve rather different purposes once you think about it. An Interface is more of a high level architectural tool (which becomes clearer if you start to grasp design patterns) - an Abstract has a foot in both camps and can perform some of the dirty work too.

Why use one over the other? The former allows for a more concrete definition of descendants - the latter allows for greater polymorphism. This last point is important to the end user/coder, who can utilise this information to implement the A.P.I(nterface) in a variety of combinations/shapes to suit their needs.

I think this was the "lightbulb" moment for me - think about interfaces less from the author's perpective and more from that of any coder coming later in the chain who is adding implementation to a project, or extending an API.

sunwukung
to build upon this: An object that implements an interface takes on it's TYPE. This is crucial. So, you can pass different variations of the interface to a class, but refer to them (and their methods) WITH THE TYPE NAME OF THE INTERFACE. Thus, you eliminate the need for a switch or if/else loop. Try this tutorial on the subject - it demonstrates the use of an interface via the Strategy Pattern.http://www.phpfreaks.com/tutorial/design-patterns---strategy-and-bridge/page2
sunwukung