views:

87

answers:

4

In context of recent trends in interviews i have noticed that this question arises every time. But when one answers the general definition then the interviewer says everyone knows it... tell something different. Further scenarios are asked where which one will be used and be beneficial and why

So kindly share any new insight into this topic.

Thanks in advance...

+3  A: 

An abstract class can define base implementations of methods along with data members that are protected or private, while an interface only defines the functionality that a class must provide along with public data members.

The way I like to look at it is that an abstract class is a foundation for other classes. It not only specifies the operations that a specific family of things has to have, but also the data that these operations need to do their work. Specific children can add (or even ignore, if needed) specific data elements. An interface, on the other hand, is a contract - it says nothing about how you are going to do something, only what things you must do and what you will make visible to the outside world. Your inner workings are your own business in an interface.

Thomas Owens
can you kindly share some scenarios for both ?
HotTester
+3  A: 

Abstract classes can provide implementations for their methods whereas an Interface strictly provides a contract (what methods an object must implement).

Abstract classes are useful in situations where you want to provide a base implementation to inheritors but you don't want an instance of your class created directly. For example, think about a car. You wouldn't want to create a generic car, but each care can share some base set of functionality:

public abstract class Car
{
    public InternalCombustionEngine Engine { get; private set; }

    public virtual void Start()
    {
        Engine.Start();
    }

    public abstract void Drive();
}

Interfaces are useful when you have some classes that may not be directly related to each other, but you want to treat in the same fashion because each has a similar set of functionality.

Justin Niessner
Clearly: An interface is somewhat like an abstract class, the differences are in general, that you may not specifiy a prototype for an interface function and a class can implement mor than one interface.
FUZxxl
+1  A: 

Here's a good article, http://en.wikibooks.org/wiki/C_Sharp_Programming/Abstract_classes

gnome
A: 

In addition to what the others have said, I look at an interface as a relationship of behaviors that are common across classes but are not in the is-a relationship. It is a way of expressing common behaviors as opposed to the inheritance of the is-a relationships. I believe this is why some call interfaces a poor man's multiple inheritance.

johnny