C#

[C#] Abstraction Class vs Interface

An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

  • An abstract class is a special type of a class that cannot be instantiated.
  • An abstract class should, however, be inherited by its subclasses.
  • Abstract classes are either partially implemented or not implemented at all. You can have functionality in your abstract class — the methods in an abstract class can be both abstract and concrete.
  • An abstract class can have constructors — this is one major difference between an abstract class and an interface.
  • You may take advantage of abstract classes to design components and specify some level of common functionality in the methods of the abstract class until a specific implementation of the abstract class is needed in the class hierarchy.
  • The constructor of an Abstract Class can be called through the derived class constructor.
  • All abstract methods must be implemented in its derived class, if inherited.

An interface contains definitions for a group of related functionalities that a class or a struct can implement.

  • We cannot create an object of an interface, we can only create a reference or Interface Variable.
  • An interface will have only abstract methods (method declaration).
  • Interfaces supports Inheritance, Polymorphism (Overloading, Overriding (using the “new” keyword to hide the interface methods above)).
  • We cannot create variables in an interface.
  • Only Properties, Indexers, Methods and Events are allowed in an interface.
  • A class can inherit multiple interfaces, which is also shown in the snapshot above.
  • We cannot create any Access modifiers with Interface Members (like private, public, protected, internal, protected internal, virtual, override, static, abstract etc.)
  • The new keyword is allowed in an interface.
  • All methods of an interface must be defined in every derived class.

You should use interface if

  • You want to simulate inheritant from struct since struct can’t inherit from another struct or class
  • If the functionality you are creating will be useful across a wide range of disparate objects
  • If you are designing small, concise bits of functionality

You should use abstract class if

  •  It applies to objects that are closely related
  • If you are designing large functional units
  • If you want to provide common, implemented functionality among all implementations of your component

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s