What is the difference between abstract class and interface?

We use abstract class and interface where two or more entities do same type of work but in different ways. Means the way of functioning is not clear while defining abstract class or interface. When functionality of each task is not clear then we define interface. If functionality of some task is clear to us but there exist some functions whose functionality differs object by object then we declare abstract class.
We can not make instance of Abstract Class as well as Interface. They only allow other classes to inherit from them. And abstract functions must be overridden by the implemented classes. Here are some differences in abstract class and interface.

  • An interface cannot provide code of any method or property, just the signature. we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract. An abstract class can provide complete code of methods but there must exist a method or property without body.

  • A class can implement several interfaces but can inherit only one abstract class. Means multiple inheritance is possible in .Net through Interfaces.

  • If we add a new method to an Interface then we have to define implementation for the new method in every implemented class. But If we add a new method to an abstract class then we can provide default implementation and therefore all the existing code might work properly.

4 comments:

Type more interview question answer here