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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With