Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interfaces vs. abstract classes [duplicate]

In C#, when should you use interfaces and when should you use abstract classes? What can be the deciding factor?

like image 718
tush1r Avatar asked Oct 04 '22 22:10

tush1r


People also ask

Why do we need interface instead of abstract class?

The short answer: An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.

Are interfaces just abstract classes?

Abstract Class. An abstract class permits you to make functionality that subclasses can implement or override whereas an interface only permits you to state functionality but not to implement it. A class can extend only one abstract class while a class can implement multiple interfaces.

What is the main difference between interface and abstract class in Java?

Abstract class can inherit another class using extends keyword and implement an interface. Interface can inherit only an inteface. Abstract class can be inherited using extends keyword. Interface can only be implemented using implements keyword.


2 Answers

Update: C# 8.0 New Feature: Beginning with C# 8.0, an interface may define a default implementation for members, including properties. Defining a default implementation for a property in an interface is rare because interfaces may not define instance data fields.

The advantages of an abstract class are:

  • Ability to specify default implementations of methods
  • Added invariant checking to functions
  • Have slightly more control in how the "interface" methods are called
  • Ability to provide behavior related or unrelated to the interface for "free"

Interfaces are merely data passing contracts and do not have these features. However, they are typically more flexible as a type can only be derived from one class, but can implement any number of interfaces.

like image 160
JaredPar Avatar answered Oct 06 '22 12:10

JaredPar


Abstract classes and interfaces are semantically different, although their usage can overlap.

An abstract class is generally used as a building basis for similar classes. Implementation that is common for the classes can be in the abstract class.

An interface is generally used to specify an ability for classes, where the classes doesn't have to be very similar.

like image 116
Guffa Avatar answered Oct 06 '22 11:10

Guffa