Introduction

In this article along with the demo project I will discuss Interfaces versus Abstract classes. The concept of Abstract classes and Interfaces is a bit confusing for beginners of Object Oriented programming. Therefore, I am trying to discuss the theoretical aspects of both the concepts and compare their usage. And finally I will demonstrate how to use them with C#.

Background

An Abstract class without any implementation just looks like an Interface; however there are lot of differences than similarities between an Abstract class and an Interface. Let's explain both concepts and compare their similarities and differences.

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. 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.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it 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 multiple inheritance, interfaces are used to implement multiple inheritance.

Both Together

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.

There are some similarities and differences between an interface and an abstract class 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. 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

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 implementation 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 constrants defined

Using the Code

Let me explain the code to make it a bit easier. There is an Employee abstract class and an IEmployee interface. Within the Abstract class and the Interface entity I am commenting on the differences between the artifacts.

I am testing both the Abstract class and the Interface by implementing objects from them. From the Employee abstract class, we have inherited one object: Emp_Fulltime. Similarly from IEmployee we have inherited one object: Emp_Fulltime2.

In the test code under the GUI, I am creating instances of both Emp_Fulltime and Emp_Fulltime2 and then setting their attributes and finally calling the calculateWage method of the objects.

Conclusion

In the above examples, I have explained the differences between an abstract class and an interface. I have also implemented a demo project which uses both abstract class and interface and shows the differences in their implementation.

Share

About the Author

Rahman is a very experienced software developer with 10+ years of experience in different programming languages. Has experience in both Web Application Development and Desktop Line of Business Application development.

At the moment his area of interest are .Net both C# and VB.Net, Client side UI frameworks like AngularJs, Bootstrap, etc. Application Architecture, Dependency Injection, Use case Driven Development, Test Driven Development, MOQ etc.

He has Bachelor of Computing with Distinction Grade from University of Western Sydney.

Comments and Discussions

Nice article. I have question. What are the characterstics which makes a class to call as an Abstact class. I believe, just naming class with "abstract" key doesn't make that class as abstract class. If one takes abstract keyword, one can create the instance of that class.

But I have one question though
In the article, you mention that
- 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.

However, this made me wondering how this is done with the IDisposable interface. It acts as an interface
but it generates code when you implement this.
in C# you see this code being generated:

The article is very good, but there is one thing that is bothering me.

You're saying the abstract classes are faster then interfaces, I doubt this and after testing on different subjects I came to the following results (each test done in 1.000.000x loop):

Creating new instances:
An class inheriting from an abstract class took 37ms to create 1.000.000 instances.
An class implenting an interface took 27ms to create 1.000.000 instances.
An struct implenting an interface took 4ms to create 1.000.000 instances.

Invoking an method:
An class inheriting from an abstract class took 28ms to invoke a method 1.000.000 times.
Both a class and struct implenting and interface took 25ms to invoke a method 1.000.000 times.

The last thing I tested on was getting a value from a field. This cannot be done in interfaces so you are forced to use properties for interfaces. (unforunatly )
It took 3ms to get a value from an integer field of an abstract class 1.000.000 times.
Both the sturct and class with an interface took 27ms to a value from an integer property 1.000.000 times.

So as long as you dont need to implent fields (which are forced to be properties for interfaces), interfaces are faster then abstract classes, especially on structs.

However, if you need to acces alot of fields (from outside the class/struct), the best choice would be an abstract class.

If you need to implent an interface, a struct would be the best choise.
(If its about speed ofcourse)

The results might be slightly off though, I ran that test in release mode, but with the debugger still attached (didin't know about it at that time).
However, I suspect that the result without the debugger would be about the same.

I am currently writing quite a big piece of software for my phD thesis. I am supposed to use it to do some kind of sample imaging on a microscope.

For this purpose my microscope(s) is/are fitted with nanopositioning stages that allow me to move my samples under the microscope in an automated way. Based on the detector I need to use I have microscopes that are either fitted with an analog or a digital nanopositioning stage.

Both types of stages allow me to do the same kind of things, but the way to "talk" to them are widely different. Analog ones have no dedicated controller and I need to send them voltages through a programmable powersource while digital ones accept ascii command strings while the translation of these commands to actual movement is handled by a dedicated controller.

Ideally I want to use one single software package to control both types of stages, because all the top level stuff is identical (displaying images, zooming in on them, telling the setup which region of the image to zoom in on, ...)

I figure I need to either use an abstract "stage" class or an "IStage" and derive both an "AnalogStage" and "DigitalStage" class that both have common methods such as "Initialize", "Move(coordX, coordY)", "Zerostage()" and so on ...

I already did something similar to define movement types for the stages where I have an abstract base class "Scan" from which I derive classes such as "ScanMultilines" and "ScanSingleLine" where the constructors accept a pair of XY coordinates for the beginning and end point of the movement and where methods in the class return all intermediate coordinates for the movement trajectory. In this case it was simple since the constructor for each movement type had the same signature and I could write the rest of my code to accept "Scan" objects end pass the correct derived class as needed.

For the "Stage" class however I am confused about the correct way to do things. The constructors will be very different in signature:

it should be written:
-- abstract class can have private members, interface cannot. Your abstract class is not secure, as parameters got just protected, and when you inherit this class... boom, that's it. Interface contain only public members as it is only interface
-- one class can inherit any numbers of interfaces and only one any class IF it comes first in declaration
-- every abstract member has to be overriden

In abstract class we need to have at least one concrete method implementation.right?Should there be also at least one abstract method in this class.What if there are no abstract method but only one concrete method.

anything one with abstract modifier within abstract class MUST be.
Abstract class can be all abstract. If so, it will look more like interface. BUT be aware!!!
Interface is a BACKBONE! It shows you what to do next, when even fully abstract class cannot say anything. Because interface MUST be FULLY implemented, when concrete methods can be added to abstract without 'feel'.

I think, because you often switch between an interface and an abstract class during development, interfaces shouldn't be named with the I prefix, so you don't have to refactor your whole project all the time.

I think, because you often switch between an interface and an abstract class during development, interfaces shouldn't be named with the I prefix, so you don't have to refactor your whole project all the time.

Interfaces and abstract (not finished) classes are used for standardization of you project or framework. It enables you to be sure, that class that implements that interface or inherits abstract class can be used that or this way. Interface has to be selected from start as it is a root of all. If touch root interface, you brake all your code.

Why are you creating these methods, which you already been define in the abstract base class? I think it is redundant, because even if you declare Emp_Fulltime emp = new Emp_Fulltime(); without implement these method the compiler will use the base class method unless you are trying to show something else.