Differences between an abstract class and an interface (abstract class and interface)


What are the differences between an abstract class and an interface?

 108
Author: StateItPrimitive, 2013-07-10

13 answers

A short difference.

An abstract class is a class that does not have one or more methods implemented (some languages require such methods to be marked with special keywords).

An interface is an abstract class that has no methods implemented, they are all public, and there are no class variables.

An interface is usually needed when only the interface (tautology) is described. For example, one class wants to give another the ability to access some of its own methods, but does not want to "reveal" itself. So it just implements the interface.

An abstract class is needed when you need a family of classes that have a lot in common. Of course, you can use the interface, but then you will need to write a lot of identical code.

In some languages (C++), there is no special keyword for interfaces.

We can assume that any interface is already an abstract class, but not vice versa.

 165
Author: KoVadim, 2017-06-07 19:44:15

Tl; dr: Abstract class - a means of developing classes at the lower level, a means for reusing code; interface-a means of expressing the semantics of the class. Thus, these are completely different, little-related concepts.


Think about it differently.

The abstract class is the "preform" of the class: most of the methods (including internal ones) are implemented, except for a few. These few unrealized methods may well be internal methods of the class, they only specify the details of the implementation. An abstract class is a means to reuse code, a means to specify which method must be overlapped in order to finish writing the class.

The interface is a kind of contract: interfaces are used in definitions to indicate that the object that will actually be used must implement (for input parameters) or will be guaranteed to implement (for output parameters parameters) a set of methods and (what is much more important!) have a certain semantics. The interface may well be empty, however, to implement the interface means to support this semantics.

Abstract classes are ideologically similar toC++ templates: both are class preforms, but the template needs to specify template types to get a class, and the abstract class needs to specify abstract methods.

Interfaces are ideologically similar to header files C++: they expose methods and hide a specific implementation.

The question of whether an interface or an abstract class is actually a class is a technical implementation detail that depends on the specific programming language. For example, in C++, there are no interfaces at all, and they have to be emulated by classes without data. Abstract class in C++ as such is also absent, but it can be considered any class with abstract methods. (Hence the C++limitation: at least 1 abstract method In C++, you can also (indirectly) instantiate an abstract class, call an abstract method, and (possibly) get a runtime error. In C#, interfaces and abstract classes are built into the language.


Example (in C#, the specific language doesn't matter):

// общий код для всех животных
abstract class АбстрактноеЖивотное
{
    public int Возраст { get; protected set; }
    public int Вес { get; protected set; }
    public bool Спит { get; protected set; }
    public void ПодатьГолос()
    {
        if (!Спит && Возраст > ВозрастПрорезанияГолоса)
            РеализацияПодатьГолос();
    }

    abstract protected void РеализацияПодатьГолос();
    readonly protected int ВозрастПрорезанияГолоса;
}

class Собака : АбстрактноеЖивотное
{
    override protected void РеализацияПодатьГолос()
    {
        Гав();
    }
    public void Гав()
    {
        // реализация
    }
    public Собака() { ВозрастПрорезанияГолоса = 2; }
}

class Кошка : АбстрактноеЖивотное
{
    override protected void РеализацияПодатьГолос()
    {
        Мяу();
    }
    public void Мяу()
    {
        // реализация
    }
    public Кошка() { ВозрастПрорезанияГолоса = 1; }
}

interface IЖивотное
{
    int ИнвентарныйНомер { get; }
}

class Лев : ОбитательЗоопарка, IЖивотное
{
    // ...
}

class Зебра : ОбитательЗоопарка, IЖивотное
{
    // ...
}

class Сторож : ОбитательЗоопарка
{
}

// ...
void Инвентаризация()
{
    List<ОбитательЗоопарка> обитатели = // ...
    foreach (var обитатель in обитатели)
        if (обитатель is IЖивотное) // отделяем животных от неживотных
            ДобавитьЖивотное((IЖивотное)обитатель);
}

void ДобавитьЖивотное(IЖивотное животное) // сюда сможет попасть только животное
{
    ...
 80
Author: VladD, 2013-07-11 09:21:51

It seems to me rather curious that this question is marked with the tag "oop", but many of the answers clearly leak specific aspects of specific programming languages. I will try to give an answer based on the concepts of OOP and only then show why this difference appeared in some programming languages at all.

Abstract classes and interfaces have a certain relationship to inheritance, more precisely to the modeling of the world. With their help, we want to express that we have a certain group of things in our system have something in common: some general behavior that distinguishes this group of gizmos from all the others.

Let's say, for example, we want to model buttons in the user interface. Since we are talking about OOP, we will highlight a certain type of Button with a certain set of operations (which define the behavior) and a hidden state that the behavior relies on (yes, there may not be a hidden state). At the same time, we can distinguish three types operations:

  • A specific fixed operation that should be absolutely stable for all types of buttons.

  • A specific operation with the default behavior (i.e., an operation whose behavior is suitable for many types of buttons, but there may be buttons with different behavior).

  • Declaration of an operation without a specific implementation (i.e., an operation whose behavior cannot be determined, since it is not known at this stage the default behavior is reasonable, or the operations may be too different for different buttons).

In other words, the Button type can contain non-virtual methods (non-virtual methods), virtual methods (virtual methods), and abstract methods (abstract methods).

Having different types of methods is a very important modeling tool and allows you to express the designer's intentions very accurately. For example, we can add a non-virtual "Button Click" operation that will delegate some of its work to a virtual (or abstract) method to "Process the click", but always perform a certain part of the work (the discerning reader will see the "Template Method" pattern in this description).

Once we've defined the base type, it's time to define arbitrary types. And then the questions begin. More precisely, there are no questions when the type has only one immediate the base type, or all base types, contain only operation declarations. No problem, inherit the "Menu Button" from the "Button" and override the "Click on Button" method. But what if our "Menu Button" type is inherited from two types with the same virtual operation? How do I redefine just one and leave the other? And what about the new type of client and distinguish which operation to call? What if the two base types have a field with the same name? What if one basic type has the "Click" method the button" implemented, and the other-only described in the form of a declaration?

No, all these problems can be solved, and in C++, and Eiffel, and other programming languages, you can quite flexibly control what and how to redefine, what to hide, what to expose, and how to call a method of a certain base type. But for the authors of some programming languages, such complexity seemed unnecessary, and they went to the trick and separated the types that contain only method declarations into a separate one category, and this is how the interfaces appeared.

Now it will be easy to distinguish between three concepts-an interface, an abstract base class, and a concrete base class.

  • Interface - describes a certain family of types and contains only declarations of operations (yes, I deliberately write the word "declaration", and do not use the word "contract", which in OOP has a very specific meaning).

  • Abstract base class describes a certain type family, but in addition to the declaration of operations, it can contain default implementations (virtual methods) and fixed operations (non-virtual methods).

  • A specific class describes a certain type family that is ready for use by clients. Such a class cannot contain operation declarations and all its operations must be either fixed (non-virtual methods) or contain a default implementation (virtual methods). There are another subspecies of specific classes – the sealed class is a type of a specific class that cannot be inherited from, which means that it can only contain specific operations.

Separating interfaces into a separate category is useful not only in terms of simplifying the implementation of programming languages, but also for highlighting different approaches to modeling. So, for example, class inheritance models the "Is" relationship ("Menu button" IS A "Button"), and base classes usually contain certain functionality that is closely related to the functionality of the derived class. Base classes not only model a group of types, but also allow you to reuse existing functionality.

Interfaces, by their nature, have less connectivity (low coupling), because they do not have specific behavior that can complicate the life of the successor class. Interfaces can also model the "Is" relationship ("Menu button" IS an "I-button"), but can also define a less rigid "CAN DO" relationship. For example, the IEquatable interface from BCL defines an "additional" behavior that says that types can compare object values.

 59
Author: Sergey Teplyakov, 2016-02-09 05:05:47

Let's take it in order. The interface is the contract / obligations that the class assumes and is obliged to fulfill them. Let's say: there is an array of classes that can say hello

std::vector <IHellower*> mArr;
class IHellower{
     virtual void Hello() = 0;
}

Now any class, regardless of its complexity, hierarchy, and scope, can inherit (assume ownership/sign a contract for execution) of this method and thus "become its own through others". The best part here is that no matter how extensive the interface is (in this context there are public methods of the class) for the class that executes this contract, only one method will be visible from this array. Example: there are many graphical classes and some of them you have taught to react to Blur-push them into 1 array of interfaces and, if necessary, call the Blur(int value) method); When using the interface, we abstract from what the class is: car, plant, air ... If he has committed to have an implementation of "Say Hello" we have guarantee that this method will be available to us through the object (the pointer of this class) (I remind you, the interface is pure virtual methods, in the public section, without variables).

And now the other side, C++, for all its power, does not have the concept of an interface at the language level. But programmers are used to the interface, it is convenient, it is safe (read about the Insertion of control) and correct (from the point of view of architecture). We have to implement the "interface" with the tools that The C++ language is an abstract class. As you have noticed, you can cram different methods (public/protected/private), member classes(in other languages, there are already problems with variables in the interface). If the interface keyword was used in C++ and was inherited clearly as in C# , there would be no such confusion. Abstract classes, just, and are used in cases of allocation of the general part of classes, but such a class itself should not be (it makes no sense to have an instance of such a class).

class SomeThingLikeABall
{
        private:
            int radius;
            int weight;
        public:
            bool canPlayFootballWithIt() = 0;
            void draw() = 0;
}

As an example, they described the ball and watermelon classes, found common features, and saw that they would still describe round objects. We separated all this into a general class and made it abstract, because why in the system should we be able to have a class "Something is round, with weight and can be thrown".

 17
Author: rikimaru2013, 2016-12-30 09:18:16

Differences between an abstract class and an interface in Java

Abstract Class Interface
Keyword used to describe To define an abstract class, use the keyword abstract To define the interface, use the keyword interface
Keyword used to implement For inheritance from an abstract class uses the keyword extends The keyword {[3] is used to implement the interface]}
Constructor The constructor definition is allowed Declaring / defining a constructor is forbidden
Default method implementation Valid Up to Java 8, only declaring methods is allowed, but implementing them is prohibited. Starting with Java 8 the implementation of static methods became valid, and the implementation of non-static methods became available through the keyword default
Fields It can have both static and non-static fields (the same applies to final) Any field of the interface is public static final by default (and cannot have any other fields).)
Access Modifiers Members of an abstract class can have any access modifier: public, protected, private, or the default access modifier (package) Interface members are public by default (and cannot have any other access modifier).)
Inheritance Can extend (extends) any other class and implement (implements) no more than 65535 interfaces Can extend (extends) no more than 65535 interfaces
 17
Author: StateItPrimitive, 2021-01-11 10:08:13

You can also add that often a class describes a certain model, and an interface describes a behavior or role. The class is called a noun (Dog, Car, House), and the interface is added to the ending-able to describe some action or property (Moveable, Eatable, Buildable). For example, we create a game in the strategy genre. We have different factions, each of them has different units (warriors, builders) and we create a separate class for each unit. But in the behavior between all these units there are many similarities - any warrior regardless of faction has the ability to fight (Attackable), any builder regardless of faction has the ability to build (Buildable), and absolutely all units have the ability to move (Moveable). In this way, you can describe the interaction of all roles using multiple interface inheritance.

 15
Author: kostyabakay, 2015-07-15 23:26:23

Can I get in )

  1. A class with a virtual function / functions is called - abstract

  2. An abstract class can have one or more pure virtual functions

  3. If an abstract class has at least one purely virtual function, an object of this class cannot be created, but only inherited. purely virtual functions must be redefined in the future.

  4. The interface of a class is an indication/agreement with the programmer about how the programmer can use this class. that is, it turns out the interface is all open (public) data that the programmer can access.

In fact, I wrote that @VladD only in simple language

ps - модераторам почему я комментировать не могу?
 11
Author: perfect, 2016-04-28 06:35:40

I'm new to OOP, but I dare say my own version of what's going on.

First, programmers invented "interfaces" - since this is a very convenient thing in OOP. And then suddenly it turned out that some different classes that implement the same interface can contain almost the same pieces of code! And throwing the same pieces of code in different places of the project is no longer good. And then they invented an "abstract class" that can perform not only the role of an interface, but also serve as an entity for allocation of common code sections – that is, to do the work that the interface could not do. That is, the "abstract class" helps to avoid code duplication – after all, one of the main methods of a programmer's work is the ability to find common code sections and "put them out of brackets", so to speak, which helps to reduce code duplication. That is, at the heart of all this is the struggle with the complexity of program development and maintenance, and the "abstract class" helps to solve this problem. the task.

 9
Author: Gordon Freeman, 2018-09-23 06:50:28
  1. In some languages (Java ... ) it is possible to inherit from several interfaces, but only from the 1st class.
  2. Interface does not implement methods, but only provides access rights for using them (You can think of an interface as a veil or a contract for access rights to something). In an abstract class, you can implement a method and override it in an inherited class, it's just that you can't create objects of this class.
 5
Author: Valery Tiurin, 2017-09-27 08:54:00

Interface is a class that is abstract by default. In fact, the interface is needed in order to inherit from it.

 5
Author: Микола Лутчин, 2017-09-29 08:32:44

An abstract class can have variables, constructors, properties, and method implementations. Interface - only method signatures.

 4
Author: Alex Petrachuk, 2017-09-27 07:56:47

What is an abstract class?

An abstract class is a class that is declared abstract-it may or may not include abstract methods. Abstract classes cannot be created, but they can be sub-classified. When an abstract class is subclassed, the subclass usually provides implementations for all the abstract methods in its parent class.

I will decipher the concept of an abstract class a little. In connection with the question why do I use abstract class. Sometimes I just add the phrase abstract to a class, because some methods must be implemented by the user of this class, and specify which immeno methods must be abstract. What is this necessary for, however, if the user uses an abstract class, then some of its methods already have a default implementation that can be overlapped, and abstract methods also overlap, only the syntax assumes the presence of the abstract modifier and the absence of the method body, thus defining only the signature. This is a feature of the language and a difference from other object-oriented languages. The phrase abstract does not necessarily imply abstractness or such an interpretation, but only the possibility of specifying methods that need to be overlapped in the descendant classes.

What is abstraction in programming?

In object-oriented programming, abstraction is one of the three basic principles (along with encapsulation and inheritance). Thanks to In the abstraction process, the programmer hides everything but the relevant object data to reduce complexity and increase efficiency.

Can an abstract class not have abstract methods?

Yes, we can have an abstract class without abstract methods, since both are independent concepts. Declaring an abstract class means that it cannot be created by itself and can only be subclassified. Declaring an abstract method means that the method will be defined in the subclass.

Can you create an abstract class object in Java?

If we could create an object of an abstract class and call its method without a body (since the method is purely virtual), it would give an error. That's why we can't create an abstract class object. In short, it is legal to have a public constructor of an abstract class. An abstract class cannot be created, but it can be used if there is a corresponding implementation of this class. Myself abstraction, unlike inheritance, involves no implementation code. If you use an abstract class, you can limit yourself to declaring methods. Interfaces are abstract classes where all methods are abstract.

 4
Author: Roman C, 2020-06-12 12:52:24

A class is always an interface + an implementation. At least partial, as in the case of an abstract class.

An interface is a way to completely separate an interface from an implementation, i.e., as a completely abstract class. It is used to describe the contract of the object's behavior when interacting with the external environment.

Interface                     Abstract Class
Relationship           Contract                     Is a
The essence of Contract Description Template for a class group
When to use Always (if you don't need state) Only when you need state
State                 No Can have
 0
Author: pazukdev, 2021-01-11 13:44:13