Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract classes vs Interfaces

Tags:

c#

I'm a bit confused about the usage of Abstract classes in C#. In C++, it makes sense to define a template which classes inheriting the abstract class can follow. But, in C# doesn't Interface serve the same purpose?

True that abstract classes can have default implementation which is not provided by Interfaces. So if implementation doesn't need to be included in base class, is it better to go for Interfaces?

like image 270
softwarematter Avatar asked Sep 24 '09 21:09

softwarematter


People also ask

What is the difference between abstract classes and interfaces?

The Abstract class and Interface both are used to have abstraction. An abstract class contains an abstract keyword on the declaration whereas an Interface is a sketch that is used to implement a class.

Which is better to use abstract class or interface?

Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing a common functionality to unrelated classes. Interfaces are a good choice when we think that the API will not change for a while.

Is every interface is an abstract class?

Abstract class and interface both can't be instantiated. But there are many differences between abstract class and interface that are given below. 1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods.


2 Answers

I still like to provide a default abstract implementation of an interface, assuming it's a substantial interface (and it makes sense). You never know when you might add something to the interface that has an easy default implementation that could be included and given "for free" to anyone who inherits from the abstract base class.

like image 107
Adam Robinson Avatar answered Sep 20 '22 04:09

Adam Robinson


This CodeProject article has a lot of information on the difference between the two including a table comparing and contrasting the features of each.

Interfaces define the contract between classes - the ways classes call each other. A class can implement multiple interfaces, but can only inherit from one abstract class.

like image 35
ChrisF Avatar answered Sep 23 '22 04:09

ChrisF