What is the use of default interface methods?


I was seeing some features proposed for C # 8 and I came across the default interface methods .


Add support for virtual extension methods - methods in interfaces with concrete implementations.

So I understand it is to allow implementations inside interfaces, but what is the use of it? Does not this conflict with the use of abstract classes?

asked by anonymous 07.09.2017 / 00:15

1 answer


In fact there is no conflict, abstract classes are classes, so a class can only be inherited from a single class. Interfaces can still be inherited as often as needed, even with standard deployment methods.

This in itself already greatly increases the utility of it since in the background almost never needs multiple subclasses, but multiple subtypes is important, and types can benefit greatly from having behaviors.

Note that interfaces will still not be able to be, so at this point it also differs from abstract classes. It is still not certain about all that the new functionality will provide, may have other limitations, for example of not having constructors, which makes sense since they are normally used to initialize state, which the interface does not have.

Code reuse increases a lot. Today the solution goes through:

  • a) implement the interface in the class with a new code written there
  • b) implement the interface with a simple delegation method for a utility method
  • c) abandon the method polymorphism capability ( extension method )

Version 8 of C # should allow none of this to be necessary and the implementation is already available for all classes that want to declare it to be of the subtype of that interface.

Some considerations can be made:

  • No interface method needs to be implemented in it, it's an option
  • The class can always override the implementation of the interface method, it will be virtual (there are ideas to allow non-virtual methods under specific conditions, but this is not right)
  • The most interesting thing for the question is that it will be possible to add a method to an existing interface and not break all the classes that implement it, as long as this new method has a default implementation, so everything can be executed.

The initial idea was to do something even better, but to keep Java 8 compatibility and be able to interoperate well in Android preferred to do almost equal to Java.

In a way, this new functionality improves the ability of extension methods, which is still useful, and may have other extension possibilities in C # 8 as well.

One cool thing is that you can make a class conform to an interface without the class even knowing this, everything in the interface will be implemented outside the class. This has advantages and disadvantages, but it will help a great deal to avoid certain design patterns that are adopted today.

07.09.2017 / 00:31