Search This Blog

Thursday, October 30, 2008

When to use Abstract Class & Interface

Interfaces are essentially having all method prototypes no definition but Abstract class can contain method definitions also.

In short Interface is a abstract class having all methods abstract.

Both abstract classes and interfaces are used when there is a difference in behavior among the sub-types extending the abstract class or implementing the interface.

When the sub-types behavior is totally different then you use an interface, when the sub-types behavior is partially common and different with respect to the super type an abstract class is used. In an abstract class the partially common behavior is given a concrete implementation. Since there is no common behavior between an interface and a sub-type an interface does not have an implementation for any of its behavior.

If you create a abstract class writing the abstract keyword in the declaration part then You only can inherit the class. You can not create an instance of this abstract class but can inherit the class and with creating the instance of the derived class you can access the method of the abstract class.

If you use a virtual keyword in a method then you can override this method in the subclass if you wish.

If you create a abstract method then you must override this method in the subclass other wise it shows error in the program.