tags:

views:

51

answers:

2

Possible Duplicate:
Interface vs Abstract Class (general OO)

What are the differences and similarities between an interface class and an abstract class?

I mean when to use interface and when to use abstract class? On what conditions are one appropriate to use over another.

+1  A: 

this link could help.

GG
In interface class you have to implement each and every function in Implementor class, but in abstract class it is not necessary because some of methods may already implemented in abstract class.
GG
@GG, great link
Starx
+1  A: 

First off, an interface is not a class. An interface cannot specify functionality but rather only the required names of things.

An interface defines what methods and properties must be publicly available in any class that inherits from the interface. An interface contains no implementation code and says nothing about any non-public aspects of the class. An interface is not a class but rather more of a contract.

An abstract class is a real class. The unique restriction of an abstract class is that it cannot be instantiated directly. Rather, you have to instantiate a subclass that inherits from the abstract class.

As to when to use them, I would say that you should consider inheriting from an abstract class when your objects really share a common ancestor. For example, it would be logical if 'salesman' and 'programmer' both inherited from an abstract 'employee' class.

Interfaces are useful when you want to know what the public interface of a class will look like but you do not require that they share any commonality in terms of implementation. For example, in C# any class that implements the IEnumerable interface can be iterated over and will certainly implement MoveNext and Current. This could be a collection like a list or an array or it could be a generator (state-machine) that calls into a database or a web service or even generates random numbers. The implementations of IEnumerable do not need to share any common code at all other than the names of methods and properties specified in the interface.

It is worth noting that, in C#, you can only inherit from a single class but you can implement as many interfaces as you like. Also, in C# interfaces begin with a captial 'I' by convention but strictly speaking this is not required.

Justin