The default implementation of the interface. What is the deep meaningful difference between an abstract class and an interface?

I know that an abstract class is a special class that cannot be created. An abstract class should only be subclassed (inherited from). In other words, it allows other classes to inherit from it, but cannot be created. The advantage is that it provides certain hierarchies for all subclasses. In simple words, this is a kind of contract that forces all subclasses to fulfill the same hierarchies or standards.

I also know that an interface is not a class. This is an object that is defined by the word Interface. The interface has no implementation; it has only a signature or, in other words, just a definition of methods without a body. As one of the similarities with an abstract class, this is a contract that is used to define a hierarchy for all subclasses or defines a specific set of methods and their arguments. The main difference between the two is that a class can implement more than one interface, but only one abstract class can inherit. Because C # does not support multiple inheritance, interfaces are used to implement multiple inheritance.

When we create an interface, we basically create a set of methods without any implementation, which should be overridden by the implemented classes. The advantage is that it provides a way for the class to be part of two classes: one from the inheritance hierarchy and one from the interface.

When we create an abstract class, we create a base class that can have one or more completed methods, but at least one or more methods remain incomplete and are declared abstract. If all methods of the abstract class are not completed, then it is similar to the interface.

BUT BUT BUT

I noticed that we will have default interface methods in C # 8.0

, , 1-2- , ?

, , ?

+9
5
+5

, - , - /.

, , . . .

+2

, .

  • "". . -
  • . . .

, "". . . FerrariClass CarWithSteeringWheel

  • , , ( ) .
  • , -
  • co- , #
  • , . , :)
  • ( ), ! # 8, , . .

.

() :

interface ILogger
{
    void LogWarning(string message);

    void LogError(string message);

    void Log(LogLevel level, string message);
}

, LogWarning LogError. , .

:

interface ILogger
{
    void LogWarning(string message) => Log(LogLevel.Warning, message);

    void LogError(string message) => Log(LogLevel.Error, message);

    void Log(LogLevel level, string message);
}

, Log. , LogWarning LogError.

logLevel "Catastrophic". # 8 LogCatastrophic ILogger, .

+2

, , , , .

abstract class LivingEntity
{
    public int Health
    {
        get;
        protected set;
    }


    protected LivingEntity(int health)
    {
        this.Health = health;
    }
}

class Person : LivingEntity
{
    public Person() : base(100)
    { }
}

class Dog : LivingEntity
{
    public Dog() : base(50)
    { }
}
+1

:

  • , - .
  • , .

, , .

0

Source: https://habr.com/ru/post/1690154/


All Articles