When to use abstract class and when to use interface

By | January 1, 2018

When to use abstract class and when to use interface

This question can be asked in many different ways, situation/scenario when to choose one over another.

Abstract Class can be used in situation:

When you want to declare feilds and assign default value to it, go for abstract class over interface.

For E.g.: When i try to declare fileds in interface gets below error, which is possible in case of abstract class.

When to use interface and when to use abstract class

When to use interface and when to use abstract class

 

When we want base class method should not be implemented by all the derived classes.  OR

When you have a requirement where your base class should provide default implementation of some methods whereas other methods should be open to being overridden by child classes use abstract classes. 

So in this situation i will choose for abstract class again, because in abstract class we can create default method (default method means method having default implementaionwhich is not possible in case of interface. If we declare any method in interface we have to implement that in all the derived classes.

For E.g.: In below example, when we try to declare default method, it gives below error, which is possible in case of abstract class.

Interface vs abstract class - default Method

                                                                        Interface vs abstract class – default Method implementation

Interface can be used in situation,

In case of, when we want to derived multiple classes from single base class, which is not possible in case of abstract class becuase .Net does not support multiple inheritance, Which can be achieved by implementing multiple interface.

For E.g.:  Multiple inheritance can be achived by using interface.

Multiple inheritance

Multiple inheritance

Multiple inheritance using classes, which is not possible.

Multiple inheritance using classes

Multiple inheritance using classes

Leave a Reply

Your email address will not be published. Required fields are marked *