Difference Between Abstract Class and Interface in C#

In this article, we will learn the difference between Abstract Class and Interface in C#.

Abstract class :

An abstract class is an incomplete class or a special class that we can’t be instantiated. The purpose of this class is to provide a sketch for derived classes and set some rules what the derived classes must implement when they inherit an abstract class.

public abstract class Product
{
    public abstract void GetName();
}

public class Shampoo: Product
{
    public override void GetName()
    {
        Console.WriteLine("Ayurvedic Shampoo");
    }
}

public class Conditioner: Product
{

    public override void GetName()
    {
        Console.WriteLine("Ayurvedic Conditioner");
    }
}

class Program
{
    static void Main(string[] args)
    {

        Product product;

        product = new Shampoo();

        product.GetName();

        product = new Conditioner();

        product.GetName();
    }
}

Output :

Ayurvedic Shampoo
Ayurvedic Conditioner

Interface :

An interface can contain only method declarations, it cannot contain method implementation.  an interface may only have declarations of events, methods, and properties. Methods declared in an interface must be implemented by the classes which have to implement the interface.

Note: A class can implement more than one interface but extend only one class.

interface IMethods
{
    void ShowResponse();
}

class program: IMethods
{

    public void ShowResponse()
    {
        Console.WriteLine("This is the sample response....");
    }

    public static void Main(String[] args)
    {
        program2 obj1 = new program2();
        obj1.ShowResponse();
    }
}

Output :

This is the sample response….

Difference between Abstract Class and Interface :

Abstract Class Interface
It contains declaration as well as definition part. It contains only a declaration part.
Not supported Multiple inheritance. Supported Multiple inheritance.
It has a constructor. It does not have a constructor.
It has static members. It does not have static members.
Supported different types of access modifiers like public, private, protected, etc. Supported only public access modifier because everything in the interface is public.
Fast Performance Slow Performance because it takes some time to search method in the corresponding class.
It contains methods, fields, constants, etc. It can only contain methods.
It can be fully, partially, or not implemented. It should be fully implemented.

That’s it, Now you are pretty clear about the difference between Abstract Class and Interface in C#.

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories