tags:

views:

917

answers:

10

Why do both the abstract class and interface exist in .Net ( or in C# ) if we can achieve the interface feature by making all the members in the class as abstract.

Is it because:

  1. Interface exists to have multiple inheritance
  2. It makes sense to have interface because object's CAN-DO feature should be placed in an interface rather base abstract class.

Please clarify

+6  A: 

They both exist because they are both very different things. Abstract classes permit implementation and interfaces do not. An interface is very handy as it allows me to to say something about the type I am building (it is serializable, it is edible, etc.) but it does not allow me to define any implementation for the members I define.

An abstract class is more powerful that an interface in the sense that it allows me to create an inheritance interface via abstract and virtual members but also provide some sort of default or base implementation if I so choose. As Spiderman knows, however, with that great power comes great responsibility as an abstract class is more architecturally brittle.

Side Note: Something interesting to note is that Vance Morrrison (of the CLR team) has speculated about adding default method implementations to interfaces in a future version of the CLR. This would greatly blur the distinction between an interface and an abstract class. See this video for details.

Andrew Hare
+20  A: 

Well, an abstract class can specify some implemetation, but usually not all of it. (Having said which, it's perfectly possible to provide an abstract class with no abstract members, but plenty of virtual ones which with "no-op" implementations). An interface provides no implementation, merely a contract.

You could certainly argue that if multiple inheritance of classes were permitted, interfaces would be largely pointless.

Personally I don't get hung up on the whole "is-a" vs "can-do" distinction for inheritance. It never gives me as good an intuition about what to do as just playing around with different ideas and seeing which ones feel the most flexible. (Then again, I'm very much a "favour composition over inheritance" guy...)

EDIT: Just as the most convenient way of rebutting lbushkin's third point in his comment... you can override an abstract method with a non-virtual one (in terms of not being able to override it further) by sealing it:

public abstract class AbstractBase
{
    public abstract void Foo();
}

public class Derived : AbstractBase
{
    public sealed override void Foo() {}
}

Classes deriving from Derived cannot override Foo any further.

I'm not in any way suggesting I want multiple inheritance of implementation - but if we did have it (along with its complexity) then an abstract class which just contained abstract methods would accomplish almost everything that an interface does. (There's the matter of explicit interface implementation, but that's all I can think of at the moment.)

Jon Skeet
"favour composition over inheritance". Well there are scenarios where the opposite is more desirable, like any kind of GUI library, where inheritance is a blessing. IMHO a well though out design based on (correct) inheritance is more useful than a design based on composition if there are sufficient hierarchies. But..inheritance is harder than composition in any case (is that a flaw of OOP, as we use it today?)
Pop Catalin
"if multiple inheritance of classes were permitted, interfaces would be largely pointless". I would disagree with that assertion. First, interfaces provide a level of decoupling that even purely abstract base classes full of virtual no-op methods can't provide. They help separate the contractual obligations of a type from the inevitable implementation-centric concerns. Second, since interfaces have no data members, they avoid the issue of diamond inheritance of data. Third, C# allows methods that implement an interface to be non-virtual (which can be useful) - abstract classes do not.
LBushkin
Sorry Jon gotta disagree with you on the multiple inheritance. As someone who's spent a lot of his life in C++, trust me, it's horrible. Most developers in C++ now use multiple inheritence in pretty much the same way as c#/java i.e one main base class plus everything else as 'mix-ins'
zebrabox
@LBushkin: Point 1: if you have an abstract base class with purely virtual methods, how is that coupling you more than an interface? Point 2: Yes, I'm not saying multiple inheritance doesn't have its downsides, nor was I calling for it... but you can write an abstract class with purely virtual methods and *no* fields. Point 3: You can seal the virtual methods of base classes: I'll edit my post to show that.
Jon Skeet
+1  A: 

You gave a good answer already. I think your second answer is the real reason. If I wanted to make an object Compareable I shouldn't have to derive from a Comparable base class. if you think of all the interfaces think of all the permutations you'd beed to handle the basic interfaces like IComparable.

Interfaces let us define a contract around the publicly exposed behavior an object provides. Abstract classes let you define both behavior and implementation, which is a very different thing.

JoshBerke
+1  A: 

Interfaces exist to provide a class without any implementation whatsoever, so that .NET can provide support for safe and functional multiple inheritance in a managed environment.

Giffyguy
A: 

An Interface defines a contract that an implementing class must fulfil; it is a way of stating that "this does that". An Abstract Class is a partial implementation of a class which is by definition incomplete, and which needs a derviation to be completed. They're very different things.

McWafflestix
The implementation of the abstract class may actually be complete already - there's no requirement that it have any abstract members. It's rarely useful to derive from an abstract class and not override anything, but it's perfectly legal.
Jon Skeet
Ah, good point; still, the definition of "abstract class" means that it cannot be instantiated, so there must be a derivation to instatiate it; I still consider that to be "incomplete" because you cannot use it by itself. Still, your point is very relevant and well taken.
McWafflestix
A: 

An abstract class can have an implementation while an interface just allows you to create a contract that implementers have to follow. With abstract classes you can provide a common behavior to their sub classes witch you can't with interfaces.

bruno conde
A: 

They serve two distinctly different purposes.

Abstract classes provide a way to have a an object inherit from a defined contract, as well as allowing behavior to be specified in the base class. This, from a theoretical standpoint, provides an IS-A relationship, in that the concrete class IS-A specific type of the base class.

Interfaces allow classes to define a (or more than one) contract which they will fulfill. They allow for a ACTS-AS or "can be used as an" type of relationship, as opposed to direct inheritance. This is why, typically, interfaces will use an adjective as they're name (IDisposable) instead of a noun.

Reed Copsey
+11  A: 

It's not a trivial question, it's a very good question and one I always ask any candidates I interview.
In a nutshell - an abstract base class defines a type hierarchy whereas an interface defines a contract.

You can see it as is a vs implements a.
i.e Account could be an abstract base account because you could have a CheckingAccount, a SavingsAccount, etc all which derive from the abstract base class Account. Abstract base classes may also contain non abstract methods, properties and fields just like any normal class. However interfaces only contain abstract methods and properties that must be implemented.

c# let's you derive from one base class only - single inheritance just like java. However you can implement as many interfaces as you like - this is because an interface is just a contract which your class promises to implement.

So if I had a class SourceFile then my class could choose to implement ISourceControl which says 'I faithfully promise to implement the methods and properties that ISourceControl requires'

This is a big area and probably worthy of a better post than the one I've given however I'm short on time but I hope that helps!

zebrabox
A: 

An interface is used for what a class can do, but it is also used to hide some of things that a class can do.

For example the IEnumerable<T> interface describes that a class can iterate through it's members, but it's also limits the access to this single ability. A List<T> can also access the items by index, but when you access it through the IEnumerable<T> interface, you only know about it's ability to iterate the members.

If a method accepts the IEnumerable<T> interface as a parameter, that means that it's only interrested in the ability to iterate through the members. You can use several different classes with this ability (like a List<T> or an array T[]) without the need for one method for each class.

Not only can a method accept several different classes that implement an interface, you can create new classes that implement the interface and the method will happily accept those too.

Guffa
+1  A: 

One important reason both mechanisms exist because c#.NET only allows single inheritance, not multiple inheritance like C++. The class inheritance allows you to inherit implementation from only one place; everything else must be accomplished by implementing interfaces.

For example, let's suppose I create a class, like Car and I subclass into three subclasses, RearWheelDrive, FrontWheelDrive, and AllWheelDrive. Now I decide that I need to cut my classes along a different "axis," like those with push-button starters and those without. I want all pushbutton start cars to have a "PushStartButton()" method and non-pushbutton cars to have a "TurnKey()" method and I want to be able to treat Car objects (with regard to starting them) irrespective of which subclass they are. I can define interfaces that my classes can implement, such as IPushButtonStart and IKeyedIgnition, so I have a common way to deal with my objects that differ in a way that is independent of the single base class from which each derives.

breitak67
Very nice analogy. +1
Milan Babuškov