Чем отличается абстрактный класс от интерфейса c
.Net developer, data scientist
Различия между абстрактным классом и интерфейсом — вопрос №7 на собеседование C# / .NET
Текст к видео «Различия между абстрактным классом и интерфейсом» на канале YouTube
На собеседовании часто можно услышать вопрос какая разница между абстрактным классом и интерфейсом. Самое время на него ответить. Ответ можно начать с объяснения ограничений абстрактных классов. Абстрактные классы кроме абстрактных методов могут иметь различное количество членов иного назначения: конструкторы, свойства, конкретные методы. Если мы наследуем абстрактный класс, то кроме абстрактных методов, которые необходимо переопределить, мы получаем доступ к остальным членам базового класса. Это не всегда удобно и не всегда логично. Например, абстрактный класс «Геометрическая фигура» может иметь абстрактный метод «Посчитать количества вершин». Для таких фигур, как «Квадрат» или «Треугольник» нет никаких проблем. Однако если мы посмотрим на фигуру «Окружность», то для неё имплементация метода «Посчитать количества вершин» может быть неоднозначна.
Также в крупных приложениях проблематично создать базовый абстрактный класс, который был бы хорошим решением для большинства ситуаций. А учитывая ограничение, что в языке C# мы можем наследовать только один класс, тяжело выработать общее решение для базового класса, которое подходил бы к большинству случаев.
В таких ситуациях интерфейсы призваны решить наши проблемы. Начнем со второй ситуации. Класс может реализовывать один или несколько интерфейсов, количество интерфейсов неограниченно, но не стоит этим злоупотреблять, чтобы не нарушить один из принципов SOLID – принцип единственной ответственности. Каждый интерфейс может декларировать определенный функционал, а классы могут реализовывать этот функционал имплементируя эти интерфейсы. Тут также стоит вспомнить о принципе разделения интерфейсов (принцип I из сокращения SOLID) – интерфейсы должны быть очень специфичны и не содержать в себе излишне много членов. Если так есть, то скорей всего кроме принципа I нарушается принцип S (единичная ответственность) и скорей всего необходимо провести декомпозицию / разделение интерфейсов.
Что касается первой ситуации, то можно создать несколько интерфейсов определяющие «поведение» геометрических фигур и применять их в зависимости от ситуации, когда это имеет смысл. Например, можно бы было создать интерфейс «У меня есть точки» и реализовать его только в классах «Треугольник» и «Квадрат». Такое «поведение» классу «Окружность» не присуще, поэтому данный класс его не имплементирует.
Чем отличается абстрактный класс от интерфейса c
Один из принципов проектирования гласит, что при создании системы классов надо программировать на уровне интерфейсов, а не их конкретных реализаций. Под интерфейсами в данном случае понимаются не только типы C#, определенные с помощью ключевого слова interface , а определение функционала без его конкретной реализации. То есть под данное определение попадают как собственно интерфейсы, так и абстрактные классы, которые могут иметь абстрактные методы без конкретной реализации.
В этом плане у абстрактных классов и интерфейсов много общего. Нередко при проектировании программ в паттернах мы можем заменять абстрактные классы на интерфейсы и наоборот. Однако все же они имеют некоторые отличия.
Когда следует использовать абстрактные классы:
Если надо определить общий функционал для родственных объектов
Если мы проектируем довольно большую функциональную единицу, которая содержит много базового функционала
Если нужно, чтобы все производные классы на всех уровнях наследования имели некоторую общую реализацию. При использовании абстрактных классов, если мы захотим изменить базовый функционал во всех наследниках, то достаточно поменять его в абстрактном базовом классе.
Если же нам вдруг надо будет поменять название или параметры метода интерфейса, то придется вносить изменения и также во всех классы, которые данный интерфейс реализуют.
Когда следует использовать интерфейсы:
Если нам надо определить функционал для группы разрозненных объектов, которые могут быть никак не связаны между собой.
Если мы проектируем небольшой функциональный тип
Ключевыми здесь являются первые пункты, которые можно свести к следующему принципу: если классы относятся к единой системе классификации, то выбирается абстрактный класс. Иначе выбирается интерфейс. Посмотрим на примере.
Допустим, у нас есть система транспортных средств: легковой автомобиль, автобус, трамвай, поезд и т.д. Поскольку данные объекты являются родственными, мы можем выделить у них общие признаки, то в данном случае можно использовать абстрактные классы:
Абстрактный класс Vehicle определяет абстрактный метод перемещения Move() , а классы-наследники его реализуют.
Но, предположим, что наша система транспорта не ограничивается вышеперечисленными транспортными средствами. Например, мы можем добавить самолеты, лодки. Возможно, также мы добавим лошадь — животное, которое может также выполнять роль транспортного средства. Также можно добавить дирижабль. Вобщем получается довольно широкий круг объектов, которые связаны только тем, что являются транспортным средством и должны реализовать некоторый метод Move() , выполняющий перемещение.
Так как объекты малосвязанные между собой, то для определения общего для всех них функционала лучше определить интерфейс. Тем более некоторые из этих объектов могут существовать в рамках параллельных систем классификаций. Например, лошадь может быть классом в структуре системы классов животного мира.
Возможная реализация интерфейса могла бы выглядеть следующим образом:
Теперь метод Move() определяется в интерфейсе IMovable, а конкретные классы его реализуют.
Говоря об использовании абстрактных классов и интерфейсов можно привести еще такую аналогию, как состояние и действие. Как правило, абстрактные классы фокусируются на общем состоянии классов-наследников. В то время как интерфейсы строятся вокруг какого-либо общего действия.
Например, солнце, костер, батарея отопления и электрический нагреватель выполняют функцию нагревания или излучения тепла. По большому счету выделение тепла — это единственный общий между ними признак. Можно ли для них создать общий абстрактный класс? Можно, но это не будет оптимальным решением, тем более у нас могут быть какие-то родственные сущности, которые мы, возможно, тоже захотим использовать. Поэтому для каждой вышеперечисленной сущности мы можем определить свою систему классификации. Например, в одной системе классов, которые наследуются от общего астрактного класса, были бы звезды, в том числе и солнце, планеты, астероиды и так далее — то есть все те объекты, которые могут иметь какое-то общее с солнцем состояние. В рамках другой системы классов мы могли бы определить электрические приборы, в том числе электронагреатель. И так, для каждой разноплановой сущности можно было бы составить свою систему классов, исходяющую от определенного абстрактного класса. А для общего действия определить интерфейс, например, IHeatable, в котором бы был метод Heat, и этот интерфейс реализовать во всех необходимых классах.
Таким образом, если разноплановые классы обладают каким-то общим действием, то это действие лучше выносить в интерфейс. А для одноплановых классов, которые имеют общее состояние, лучше определять абстрактный класс.
C# Abstract class Vs Interface: Uses And Differences With Examples
In this article, We are going to discuss the “difference between Abstract class and Interface in C#” with simple examples. This is one of the most frequently asked questions in almost every C# dot net interview.

Table of Contents
C# Abstract class Vs Interface
An abstract class can provide a partial implementation and can have both abstract and non-abstract methods , while an interface only defines method signatures without any implementation. A class can inherit from only one abstract class but can implement multiple interfaces.
In Short, An abstract class allows you to create functionality that subclasses can implement or override. An interface, on the other hand, only allows you to define functionality rather than implement it. In addition, While a class can extend only one abstract class, but can have multiple interfaces.
- The abstract class and interface are used to achieve abstractions. (In C#, Abstraction is the process of defining the essential details to call methods without exposing the implementation details.)
- If complex functional units are not your objective, an interface might be more appealing. Use abstract classes if you want to extend the class hierarchy in the future
Both abstract class and interface have their own advantages and disadvantages. So, without further ado, let us take a closer look at the abstract class and interface in depth.
First, Let`s take a look at the following list of differences between the abstract class and the interface.

What’s new about the interface in C# 8.0
So let’s try to explore the new features of the Interface introduced in C# 8. We will try to understand how we can use these features in our projects with simple examples.
Default Interface Methods Introduced In C# 8.0
The Default interface method which is also known as the virtual extension method is a new feature introduced in C# 8.0
It allows an Interface to add a method with implementation without breaking the existing functionality. Before C# 8 an interface was allowed to contain only (signature) the declaration part of methods, properties, events, or indexers, but now after C# 8.0 interface can contain both the declaration and the implementation.
Example of the default interface method
The following is a simple program to illustrate the concept of the default interface method in C# 8

In the above program, we can see that we have provided the implementation for the method “DefaultInterfaceMethod” in the interface itself. Here, “MyClass” does not need to implement this method.
Here, we call the “DefaultInterfaceMethod” method with the help of the “IDefaultInterface” interface reference variable. If we try to call the “DefaultInterfaceMethod” method with the class object we will get the following compile-time error.
Change the IDefaultInterface to MyClass, as shown in the below screenshot.

The above sample program produces the compile-time error because the “MyClass” does not contain a member “DefaultInterfaceMethod”.
This is proof that the inherited class “MyClass” does not know anything about the default Interface method.
The default interface methods will only work or be accessible if the class is contextually treated as an interface.
To access the default method of the interface, we must upcast the “myClass” object to the “IDefaultInterface” interface as follows.
Access Modifiers In Interface C# 8.0
Before C# 8.0, Interface members can have implicitly default public access modifier only. Modifiers like private , public , protected , internal , virtual , and abstract were not allowed in an Interface.
For additional information on access modifiers in C#, see this link.
Example of Access Modifiers In An Interface

Important Key Points About An Interface In C# 8.0
- An interface can have only the declarations part that is no longer true. After C# 8.0 , the Interface can implement code for methods, properties, events, or indexers.
- In C# 8, interface members can have access modifiers such as private , public , protected , internal , virtual , abstract , override , static , and sealed .
- In C# 8, the Interface can have fields, but only if they are static.
- In C# 8, An interface can have default methods but the derived class inherited by the Interface does not know anything about the existence of the default methods also class does not contain the implementation code of the default method defined in the Interface.
- The default interface members are not inherited in the derived class in C# 8.
To learn more about Interface, please refer to this article: C# 10 new features
Q: Can you instantiate an interface in C#?
An interface can’t be directly instantiated in C#. However, we can access the data members of an interface by creating an object of the implementing class and then assigning the object to the reference variable of the interface it implements.

The following is a simple example to understand.
Q: Why can’t we instantiate an abstract class in C#?
No, we can’t create an instance of an abstract class because it is an incomplete class. All the members of an abstract class are not fully implemented but partially implemented. We can create an object of a fully implemented class only.
Q: Can an interface have a constructor?
No, the Interface can’t have constructors as there are no instance data members (fields) in the interface for initializing through the constructor. Constructors are generally invoked during object creation and we are not allowed to create an instance of the interface so, it doesn’t make sense to have a constructor in an interface.
Q: Why abstract class is used in C# .NET?
An abstract class is generally used to provide a template, blueprint, or a set of common rules that all the derived classes must follow and implement.
The purpose of the abstract class is to provide the default functionality to all the derived classes. It can contain both abstract and concrete methods that should be open for overriding by the derived classes.
Q: Can we declare the abstract method as static?
No, We can’t declare an abstract method as static because overriding is not possible with static methods.
Q: Can you inherit multiple interfaces in C#?
Yes, A class can inherit (implement) multiple interfaces in C#.
Q: Is it compulsory for the abstract class to have at least one method as an abstract?

No, it is not necessary to declare an abstract method inside an abstract class.
Q: When to use an abstract class vs interface in C#?
The quick answer is that you can use an abstract class to design functionality that subclasses can implement or override. On the other hand, you can only specify the functionality with an interface, not implement it. A class can extend just one abstract class, but it can extend several interfaces.
Summary:
In this article, we learned about the ‘difference between the Abstract class and Interface in C#‘ with simple examples. Also, we learned the new features in an Interface introduced in C# 8.
I hope you found this post useful in learning about Abstract class and Interface in C#. Your comments, suggestions, and constructive criticism are much appreciated.
Recommended Articles:
We would love to hear your thoughts on this post. Please leave a comment below and share it with others.
Abstract Class vs. Interface — C#
![]()
This article will cover some of the main differences between an abstract class and an interface in C#. Abstract classes and interfaces are both used to create abstraction. Abstraction in C# is the process of defining the essential details to call operations (i.e., methods) without including the implementation details.
Abstract Class vs. Interface
These are the main differences between an abstract class and an interface that you will run into when using them.
Access Specifier
An interface can not specify the access level for methods or properties like protected or private, and they are public by default. An abstract class can limit the access level for methods and properties. The only exception is an abstract method that can not be private.
Constructors
An interface can not have the declaration of constructors. If attempted, it treats them as different methods making the script implement both. An abstract class can have the declaration of constructors.
Fields
The interface can not have standard fields. They have to be properties with a get and set. The abstract class can have standard fields and properties.
Implementation
An interface only has abstract methods, which means it can only have the method’s signature and not the implementation. An abstract class can have complete methods and abstract methods.
Inheritance
C# doesn’t support multiple inheritances. A class can only inherit from one other class, but we can get around this by using interfaces. A class can inherit from multiple interfaces.
Making Changes
When making changes to an interface, all inheriting scripts have to be changed to implement the changes or throw an error. When making changes to an abstract class, unless the added change was an abstract method, there is no need to change any other code since you can add the base implementation.
Both interfaces and abstract classes are great object-oriented programming concepts. Which one you use depends on the need of the method implementations. An interface is used when you need the signature of a method and not the implementation. An abstract class is used when you do require a base implementation of the method.