AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Tuesday, 12 June 2018

When to use interfaces and when to use abstract classes?

In current article we will discuss, When to use interfaces, and when to use abstract classes? Most of the time developers are confused on design time weather to use interface or abstract class.
when to use abstract classes?
When we talk about abstract classes we are defining characteristics of an object type specifying what an object is.

When to use interface?
When we talk about an interface and define capabilities that we promise to provide, we are talking about establishing a contract about what the object can do.

Here I am listing the differences between Interface and abstract class

 Feature
 Interface
 Abstract
 Multiple inheritance
Supported
Not supported
 Implementation
Not provided
It supports default implementation
 Access Modifiers
An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public
An abstract class can contain access modifiers for the subs, functions, properties
 Core VS Peripheral
Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.
An abstract class defines the core identity of a class and there it is used for objects of the same type.
 Homogeneity
If various implementations only share method signatures then it is better to use Interfaces.
If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
 Speed
Slow compare to Abstract class
Fast
 Adding functionality (Versioning)
 If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
 If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

 Fields and Constants
No fields and constants can be defined
It can have fields and constants defined 

I hope this article will understand you to When to use interfaces, and when to use abstract classes.

   1 comment :

  • Popular Posts
  • Comments