Difference between abstract class and interface

In this article, we will discuss Interfaces versus Abstract classes. The concept of Abstract class and Interface is a bit confusing for beginners of Object Oriented programming. Therefore, I am trying makes it simple by covering theoretical concept with some working code examples. After reading this you will be having a clear concept about how to use interface and abstract class in real world projects. Let’s begin…

Abstract class and Interface

Abstract classes without any implementation just look like Interface. However, there are lots of differences than similarities between an Abstract class and an Interface. For better understanding first we will go through a brief explanation of both concept and after that, we will compare their similarities and differences.

Read Also: Basic OOP(object oriented programming) concept in C# (CSharp).

What is the Abstract class?

They are classes that cannot be instantiated, and are frequently either partially implemented, or not at all implemented. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards. It can be used to create different versions of a product because if additional functionality is needed in derived class, it can be added to the base class without breaking code.

Read Also: Magical Tips To Improve Coding Speed.

What is Interface?

An interface is an entity that is defined by the word ‘Interface’. An interface has no implementation; it only has the signature or in other words, an interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the ‘what’ part of the syntactical contract and the driving classes define the ‘how’ part of the syntactical contract.  Interfaces contain only the declaration of the members. It is the responsibility of the driving class to define the members.

Abstract versus Interface

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or its defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiples inheritance, interfaces are used to implement multiples inheritance.

Read Also: C# 7 Features and High-level overview.

List of similarities and differences between abstract class and interface:

There are some similarities and differences between an  abstract class and interface that I have arranged in a table for easier comparison:

Feature Interface Abstract class
Multiple inheritance A class may inherit several interfaces. A class may inherit only one abstract class.
Default implementation An interface cannot provide any code, just the signature. An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers 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. 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 behavior or status then abstract class is better to use.
Speed Requires more time to find the actual method in the corresponding classes. 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 implementations and therefore all the existing code might work properly.
Fields and Constants No fields can be defined in interfaces. An abstract class can have fields and constants defined.

Coding Example:

The following example demonstrates the difference between Abstract class and interface: Here we have ‘Blog’ abstract class and ‘IBlog’ interface. ‘TechnicalDiary’ and ‘TechnicalDiary2’ are child classes which inherit members of ‘Blog’ class and ‘IBlog’ interface respectively.

Abstract class

using System;

namespace AbstractAndInterface
{
    //abstrct class
    public abstract class Blog
    {
        //we have some field in abstract class
        protected string name;
        protected string slag;
        protected string niche;

        //we have some property in abstract class
        public abstract string Name { get; set; }
        public abstract string Slag { get; set; }
        public abstract string Niche { get; set; }

        //we have some complete method in abstract class
        public string AddArticle()
        {
            var message = "You added one article in TechnicalDiary";
            return message; 
        }
        public string UpdateArticle()
        {
            var message = "You have updated an article in TechnicalDiary";
            return message;
        }

        //here we have decleared some abstract methods...
        //we will define this methods in subClass.....
        public abstract string SeachArticle();
        public abstract string DeleteArticle();
    }
}

 Interface

using System;

namespace AbstractAndInterface
{
    public interface IBlog
    {

        //we can't use access specifier in Interface.
        //Only we can declare methods, propety etc...
        //if we define it, it will give error.

        //If we add fields it will give errors..
        //So I commented these fields.
        //private string name;
        //private string slag;
        //private string niche;

        //Here we can give only signature of properties.
        //if we give defination of these properties it will give error
        //we will define these methods in sub class
        //we can't use any access modifier in Interface.
        string Name { get; set; }
        string Slag { get; set; }
        string Niche { get; set; }

        //here we can't have implementaion
        //can't have virtual
        string AddArticle();
        string UpdateArticle();
        string SeachArticle();
        string DeleteArticle();
    }
}

Child class inherits abstract class members.

using System;

namespace AbstractAndInterface
{
    public class TechnicalDiary: Blog
    {
        //need to implement inherited abstract members..
        //if we don't implement it will give error..

        //override inherited abstract property
        public override string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        //override inherited abstract property
        public override string Slag
        {
            get
            {
                return slag;
            }

            set
            {
                slag = value;
            }
        }

        //override inherited abstract property
        public override string Niche
        {
            get
            {
                return niche;
            }

            set
            {
                niche = value;
            }
        }

        //method alredy implemented in abstract class
        public new string AddArticle()
        {
            return base.AddArticle();
        }

        //method alredy implemented in abstract class
        public new string UpdateArticle()
        {
            return base.UpdateArticle();
        }

        //here we overide abstract method.
        public override string SeachArticle()
        {
            return "Redirect to search result page.";
        }

        //here we overide abstract method.
        public override string DeleteArticle()
        {
            return "Hey, don't delete any article.";
        }

        ////we can define 'GuestArticle()' which is not
        //inherited from abstract method.
        public string GuestArticle()
        {
            return "Welcome guest: your can write your article.";
        }
    }
}

Child class inherits Interface members.

using System;

namespace AbstractAndInterface
{
    public class TechnicalDiary2:IBlog
    {
        //fields are defined here because
        //interface can't have fields!
        protected String name;
        protected String slag;
        protected String niche;


        //need to implement inherited abstract members..
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        public string Slag
        {
            get
            {
                return slag;
            }

            set
            {
                slag = value;
            }
        }

        public string Niche
        {
            get
            {
                return niche;
            }

            set
            {
                niche = value;
            }
        }

        //defination of interface methods
        public string AddArticle()
        {
            return "you are in AddArticle method.";
        }

        //defination of interface methods
        public string UpdateArticle()
        {
            return "you are in UpdateArticle method.";
        }

        //defination of interface methods
        public string SeachArticle()
        {
            return "you are in SearchArticle method.";
        }

        //defination of interface methods
        public string DeleteArticle()
        {
            return "you are in DeleteArticle method.";
        }

        //we can define some other methods which are not
        //decleared in Interface.
        public string GuestArticle()
        {
            return "Welcome guest: your can write your article.";
        }
    }
}

Conclusions:

Here, I have covered “difference between Interface and Abstract class” in theory. Now I am working on Coding example. Soon I will update this article with working code example. If you feel I need to modify or add something in this post please comment below. Please Keep in touch for more updates.

 

S Sharif

Founder of Technical Diary. Software engineer and passionate about technologies to learn and share. Crazy about best practices and new technology. I have worked in C#,ASP.NET MVC, HTML5, AngularJs SharePoint and SQL Server. I always try to keep myself updated and learn and implement new technologies. You can connect me on Twitter Facebook LinkedIn.

You may also like...

1 Response

  1. Jason says:

    Not to nit-pick, but we “implement” an interface, no “inherit from” an interface. Otherwise a nice discussion on the both abstractions. I use them both. Typically I will use them both. I’ll use interfaces unless I suspect that that at some point a concrete implementation will be needed by its descendants. In that case an abstract class is the way to go.

Leave a Reply

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