Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between an interface with default implementation and abstract class? [duplicate]

C# 8.0 has introduced a new language feature – default implementations of interface members.

public interface IRobot
{
    void Talk(string message)
    {
        Debug.WriteLine(message);
    }
}

The new default interface implementations provides the elements of the traits language. However is is also blurring the line between what is an abstract class and what is an interface.

What is now the benefit of using an abstract class instead of an interface with default implemenation?

like image 419
Postlagerkarte Avatar asked Sep 26 '19 11:09

Postlagerkarte


People also ask

What is the difference between an interface with default method and an abstract class?

An abstract class can override Object class methods, but an interface can't. An abstract class can declare instance variables, with all possible access modifiers, and they can be accessed in child classes. An interface can only have public, static, and final variables and can't have any instance variables.

What is the difference between abstract class and implementation class?

Type of variables: Abstract class can have final, non-final, static and non-static variables. The interface has only static and final variables. Implementation: Abstract class can provide the implementation of the interface. Interface can't provide the implementation of an abstract class.

What is the difference between the interface and the implementation in a class?

An interface is an empty shell, there are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern. The implementation is the actual substance behind the idea, the actual definition of how the interface will do what we expect it to.

What is the interface difference between abstract and interface?

The main difference between an abstract class and an interface, is that abstract class is inherited (extended), as normal class, so you cannot extend two of them in parallel, while you can implement more than one interface at the same time.


1 Answers

Funny enough, but the CLR implements default interfaces as abstract classes. CLR supports multiple inheritance. Here is a good article about this.

In C#, you need default interfaces when you need to implement (in this case actually inherit from) multiple interfaces, because the language doesn't let you inherit from multiple classes.

An abstract class also allows you to have state. State, i.e. fields, are not allowed in interfaces.

like image 173
Nick Avatar answered Nov 13 '22 12:11

Nick