Monday 9 December 2013

When we used abstract class and when we used Interface?

Abstract class has some methods are abstract. Interface is fully abstract class and all method in interface are abstract.
When we used Abstract class?
Consider a case, There is abstract base class and two child classes are inherited that abstract method in base class. Suppose if you want to add one abstract method in base class then you have to define that method in both child class compulsory.so, you have to rewrite child code again. But it is possible that you write concrete method in abstract class and no need to change child class logic.

But, you thinks that same case for interface then, child class have to implement that method. Every time you add method in interface then you have to modify child at that time, and that thing is tedious in case of reusable component. Suppose you create on DLL(that content one interface) and both child class used that. and suppose you add on method in interface then you have modify child DLL.

When we used Interface?
Interface is one kind of contract. Contract means class which implement that interface have to define all method in that class. This thing is useful in case of on class have to implement some method compulsory. Example idisposable interface have dispose() abstract method and class which is implement IDisposable interface then class have define dispose() method.

means, Abstract class is useful in case of where you don't want to modify child class later. Interface is used where some contract(agreement) have to follow by child class.

No comments:

Post a Comment