I am looking at news in Java 8 compared to 7 and in addition to very interesting things like lambdas or a new temporary structure, I found that a new function (?) Was introduced: default methods .
I found the following example in this article :
public interface Math { int add(int a, int b); default int multiply(int a, int b) { return a * b; } }
It seems very strange to me. Above, the code looks like an abstract class with an implemented method. So why introduce default methods in an interface? What is the actual advantage of this approach?
In the same article, I read this explanation:
Why do I need to add methods to interfaces? Well, this is because interfaces are too closely related to their implementation classes. those. it is impossible to add a method to an interface without violating the implementation class. After adding a method in the interface, all its implemented classes must declare the method body of this new method.
Well, that doesn't convince me at all. IMHO I believe that when a class implements an interface, obviosly should declare a body of methods for each method in it. This is certainly a limitation, but it also confirms its "nature" (if you understand what I mean ...)
If you have common logic for each inheriting class, you will put it in the implementing class abstract .
So what is the real advantage of the default method? (this looks more like a workaround than a new feature ...)
UPDATE I understand that this approach is intended for backward compatibility, but it still does not convince me that way. The interface represents the behavior that the class MUST have . Thus, a class that implements a certain interface certainly has this behavior. But if someone can arbitrarily change the interface, this restriction will be violated. Behavior can change at any time ... Am I wrong?
java programming-languages java-8
davioooh
source share