Abstract Class Vs Interface In C#

In this article, we are going to learn about what is the basic difference between Interface and Abstract Class in C#.

Difference between Abstract Class and Interface

 

Abstract Class

Interface

 Keyword Abstract keyword is used. Interface keyword is used.
Constructor Abstract class contains a constructor. The interface doesn’t contain a constructor.
Provides Abstraction doesn’t provide full abstraction. The interface provides full abstraction.
 Can have fields? An abstract class can have fields. Interface can’t have fields.
Multiple inheritances Multiple inheritances are not achieved by an abstract class. Multiple inheritances are achieved by an interface.
 Can Inherit? It can be inherited from another abstract class or interface.

Only inherit from another interface, Can’t be inherited by another abstract class.

Access modifiers Contain different types of access modifiers like public, private, protected, etc. Contains only public access modifiers.
Performance  The performance of abstract class is faster. The performance of the interface is slow because it acquires time to search the actual method.

Let us understand with some examples.

Example 1

Create Interface and Abstract Class.

//interface
public interface IStudent
{

}
//abstract class
public abstract class Student
{

}

Example 2

Try to create a constructor in the Abstract class and Interface.

//abstract constructor
public abstract class Student
{
  public Student()
  {
    Console.WriteLine("Hello i am abstract constructor");
  }
}
//interface constructor
public interface IStudent
{
  //It gives error
  public IStudent()
  {
    Console.WriteLine("Hello i am interface constructor");
  }
}

Example 3

Abstract class and Interface can have fields?

public abstract class Student
{
  int i=10;
}
public interface IStudent
{
  int i=10;//it gives compile error "Interfaces cannot contain fields"
}

Example 4

Multiple inheritances are possible in Abstract class and Interface?

public interface IStudent1
{
  
}
public interface IStudent2
{
  
}
public class StudentClass:IStudent1,IStudent2
{
  
}

public abstract class Student1
{
  
}
public abstract class Student2
{
  
}
public class StudentClass:Student1,Student2//it give error
{
  
}

Example 5

Does implementation is possible in the Abstract class and Interface?

public abstract class Student  
{  
    public void Print1()  
    {  
    }  
}  
  
public interface IStudent 
{  
    //gives error
    void Print2()
    {  
    }  
}

That’s it.

Also, check Constructors And Its Type In C#

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories