Please go to DobbyKim’s Question of the Day for more questions

A:

And it isn’t. Prior to the release of Java 8, all methods in interfaces could only be abstract methods with the public Abstract modifier, but since Java 8, interfaces have been allowed to have default methods of entities declared with the default keyword.

Example code:

public interface Func {
    
    void f1(a);
    
    void f2(a);
    
    default void f3(a){
        System.out.println("hello"); }}Copy the code

Why did Java8 add default methods for interfaces later?

Consider a question:

If I use third-party interface to extend the functionality of the interface, and add a method, and then use the third-party library user code is not available, the reason: I use third-party interface added an abstract method, then I realized that the interface class must implement the new abstract method, otherwise it will be an error. This is where backward compatibility leads to problems.

The Java language is designed with single-inheritance + interfaces as a solution to ambiguities like C++ multi-inheritance. And the default method of the interface is actually a Java ambiguity to compromise, in order to enhance the scalability of the interface and satisfy the backward compatibility, Java has to design the interface of the default method, so that not only meet the extensible ability of the interface, also meet the backward compatibility, user can not change the code under the condition of enjoy iterative upgrade software functions.

However, as we’ve already mentioned, Java’s design of default methods is a compromise on ambiguity.

The biggest drawback of C++ multiple inheritance is ambiguity. Ambiguity occurs when a derived class inherits from multiple parent classes that have the same parent class (as shown in the diamond structure above) and the derived object needs to call the methods of the ancestor class.

Since Java 8, default methods have been introduced in interfaces. As we know, a class can implement multiple interfaces, and when default methods can be declared in interfaces, problems like diamond inheritance inevitably arise.

So the addition of default methods to the Java8 interface has both advantages and disadvantages.