I was reading about the new features of C # 8 and I came across Default Interface Implentations , that is, standard implementations in interfaces.
The code below exemplifies
public interface IBankAccountManager{
void PerformTransaction(decimal amount, string reason);
void PerformDebit(decimal amount, string reason){
PerformTransaction(-1 * amount, $"Debit: {reason}");
}
void PerformCredit(decimal amount, string reason){
PerformTransaction(amount, $"Credit: {reason}");
}
}
As we can see, the PerformDebit
method has, in addition to the contract, a default implementation, which executes the PerformTransaction
method.
I'm wondering if this does not preclude the basic purpose of an interface, which is to establish a contract, not an implementation.
This type of situation is common in an abstract class, which can have both implementations and abstract methods that must be overwritten ( override
).
The example would be the implementation below:
public abstract class BankAccountManager
{
void PerformTransaction(decimal amount, string reason) { }
void PerformDebit(decimal amount, string reason)
{
PerformTransaction(-1 * amount, $"Debit: { reason}");
}
void PerformCredit(decimal amount, string reason)
{
PerformTransaction(amount, $"Credit: {reason}");
}
}
Returning to the interface case, it seems to me that it has somewhat eluded the purpose of an interface. I was then researching the OO literature about it:
An interface contains settings for a group of features related functions that a class or a struct can implement.
And below in link :
The interface does not provide any functionality that a class or a struct can inherit in the way that it can inherit functionality from the base class
That is, in Microsoft link contradicts itself.
Other references:
An abstract class can contain logic (code), whereas a interface can only specify which methods or properties (in the case of .NET) a class that implements the interface should define.
And we have the question "In OOP, can an interface have attributes?" in-oop-an-interface-can-have-attributes
You have the following answers:
1)
An interface is a "purely abstract class", which only specifies a type but does not accomplish it.
2)
In general, no. But nothing prevents a language from determining that it can. It would be strange, but it can. It would probably cease to be exactly an interface, even if it kept the name.
@Maniero's second answer makes sense, it may not seem right, but there's nothing saying it can not be done. In the Wiki :
In object-oriented programming, the interface of an object consists of of a set of methods that an object must support.
I saw that in Java, as of version 8, also has the Default Methods , which is the same functionality as implementing code in the interface .
Still, two doubts:
-
Why not use an abstract class instead of a Default Method to implement code in methods?
-
What scenario would be useful to implement in the interface and which can not be done with an abstract class?