Monday 23 May 2016

Abstract Class vs interface in Csharp


Abstract Class
Abstract Class is a class that is used as a base class and contains common methods that can be defined by class that inherits from this Base Class .  We can only inherit abstract class But We cannot instantiate Abstract Class . Abstrac classes contains both incomplete & complete methods . Means it can contains functions with definitions as well as abstract methods with only declarations . It can also contains Data Members along with subs , propreties and methods .

Interface :
Interfaces Contains only Declaration / Signature of Functions and does not contains definition of functions . Unlike Abstract classes Interfaces cannot contain complete methods or methods with definition it only contains signature of methods means only declarations
Interface also supports multiple inheritance that is not supported by Abstract classes

Difference Between Abstract Class and Interface -


Abstract Class
1. Abstract Class Can Contain Complete (functions with definitions) or Incomplete(Abstract) Members
2. Abstract Class cannot be instantiated
3. Abstract Class Can contain Data members
4. Abstract Class Can have Constructors . We Can Have Parameterized Constructors also in Abstract Class

Example :-
public abstract class ABC
{

int _a;
   
  //Parameterized Abstract Class Constructor
  public ABC(int a)
  {
    _a = a;

   }

  //Default Constructor
  public ABC()
  {
   // Code Logic

   }
public abstract void computeA(); };
public class Foo : ABC
{
    // Always pass 123 to the base class constructor
    public Foo() : base(123)
    {
    }
}
5. Incomplete members of Abstract class Means Abstract Members are Virtual Means it can be overridden by Derived Members
6. Abstract Members Cannot be Static
7. Complete Members Can be Static
8. Abstract Members can use Access Specifiers

All Private , Protected and Public Access Specifiers can be used with Abstract Class Methods . Purpose of Create Private Methods in Abstract Class is similar to normal class . These methods are used by other public methods of Abstract class as we know we can also define methods in abstract class.

Interface
1. Interface Can only Contain only Incomplete Methods that means methods with only Declaration without any definition
2. Interface cannot be Instantiated
3. Interface cannot contain data members
4. Interface cannot have constructors
5. there is no virtual member in interface as we cannot provide definition of member function in interface only inheriting class can define that function
6. Interace Cannot have Static Members
7. Complete Member does not exist in Interface
8. Interface member are public and we cannot set any access modifier to interface members

Share this

0 Comment to "Abstract Class vs interface in Csharp"

Post a Comment