views:

65

answers:

3

Possible Duplicates:
Abstract classes vs Interfaces
Abstract class and Interface class?

Hi All, I have little bit confusion about the use of the abstract class and Interface, when we need to Implement abstract class and when Interface.

Thanks Vijendra Singh

A: 

With an interface you declare a behavior without providing an implementation. This is the best thing to use as a parameter for methods, as you rely on behavior, not on a given implementation (even partial with an abstract class).

Abstract classes are best used as a base class providing a set of common functionality used by many classes implementing an interface for example. I would advise to treat this base abstract class as an internal implementation helper.

jdehaan
A: 

This has been already discussed multiple times refer this-

Implement Abstract Classes when you want some default behaviour to be inherited by all the classes as it makes more sense then to use abstract classes.

Implement Interfaces when you want to have some specific functionality for only some your classes and dont need it to be inherited.

Misnomer
+1  A: 

In general:

Interfaces should be used in any situation where what's important is what the class does, not necessarily what it is. A class that can, for instance, create a copy of itself can do many other things besides, but when you only care about being able to copy the object, you only care that the object implements ICloneable. Also, interfaces are useful when the implementation of a set of functionality is not shared; the ability to output the results of a calculation, for instance, may be in the form of a file, or the console, or over the network. These three implementations are totally different, but they can all look the same to a class that needs an IOutputWriter.

Abstracts are generally used to share code. An abstract class, unlike an interface, can specify method logic that its children can use. A BitmapImagePrinter works specifically with a Bitmap file type, but it needs the same logic as a JpegImagePrinter to actually access the printer; so, that logic can go in AbstractImagePrinter. Abstracts are also useful when what a class is is more important than what it does. CheckingAccount and SavingsAccount are both BankAccounts, even though they behave differently.

There are some other special cases where you MUST use one or the other, but on the whole, that's the major difference.

KeithS