C# – Abstract Class vs Interface

Abstract Class:

  • An abstract class is one that is intended only to be a base class of other classes, and the “abstract” modifier is used to make a class abstract. An abstract class cannot be a sealed class. An abstract method cannot be private. The access modifier of the abstract method should be same in both the abstract class and its derived class. An abstract method cannot have the modifier virtual. Because an abstract method is implicitly virtual.
  • An abstract class can have abstract members as well non abstract members.
  • It can have constants, read only variables, instance variables and static variables.
  • We cannot create an object of abstract class.
  • Abstract class contains Constructors.
  • Only Complete Member of abstract class can be Static.
  • A class can inherit only one abstract class.
  • A class inheriting an abstract class has to override the abstract methods from abstract class while implementing them.
  • We go for Abstract classes on such situations, When we have a requirement where our base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.

Interface:

  • An interface is an entity that is defined by the word Interface, it is not a class. An interface contains only the signatures of methods. Interface members cannot have any access specifier like public, private, protected, internal or protected internal. By default all the members of an interface are Public.
  • In an interface all the members are implicitly abstract.
  • It cannot have member variables.
  • We can create an object of interface by type casting it to class name.
  • Interface doesn’t contains Constructors.
  • Member of interface can not be Static.
  • A class can implement any number of Interfaces.
  • A class implementing an interface has to implement all the methods of the interface compulsorily.
  • We go for Abstract classes on such situations, If our child classes should all implement a certain group of methods but each of the child classes is free to provide its own implementation then use interfaces.

These are the basic differences between abstract class and interface.

Leave a Reply