← back to code snippets


Interface or Abstract class

Posted on August 12th, 2014

“An Abstract class without implementation just looks like an Interface..”


Abstract Classes

What’s an Abstract Class?

  • Special kind of class that can NOT be instantiated
  • It is only inherited from
  • It forces certain hierarchies for all the subclasses
  • It can be seen as a kind of contract that forces all subclasses to carry on the same standards

Why Create Abstract Class?

  • When we create an abstract class, we create a base class that may have one or more methods ALREADY completed, but also at least one or more methods uncompleted, and declared “abstract”.
  • If all methods of an abstract class are uncompleted, then it is the same as an interface.
  • The purpose of an abstract class is to provide a base class definition for how a set of derived classes work, and then allow programmers to fill in the implementation within the derived class.

Interface

What about an Interface?

  • This is NOT a class
  • It’s an entity defined by the word Interface
  • It has NO implementation
  • It only has the signature: the definition of the methods without the body.
  • It is also a kind of contract, defining a specific set of methods and their arguments

Why Create an Interface?

  • When we create an interface, we are creating a set of methods without implementation that MUST be overridden by the implemented class.
  • Advantage: It provides a way for a class to be part of TWO classes! One from inheritance hierarchy and one from the interface. 

A Couple Differences

  • A class can implement more that one interface, but can ONLY inherit from ONE abstract class
  • In C#, multiple inheritance is not supported, so interfaces are used to implement multiple inheritance.

Source: Codeproject