Default methods in Java 8

Author: Tangyuan

Personal blog: javalover.cc

preface

Hello, I'm tangyuan. Today I bring you the default method in Java 8. I hope it can help you. Thank you

The article is purely original, and personal summary will inevitably make mistakes. If so, please reply in the comment area or send a private message backstage. Thank you

brief introduction

Before Java, the interfaces we came into contact with only defined methods and did not implement methods

(look at the following people, do they look like interfaces)

But it's different in Java 8, because the default method is added to the interface

In this way, some work can be done by the interface itself instead of the implementation class (Java, you are buying people's hearts)

Let's introduce the relevant knowledge points of the default method in the form of question and answer (it is said that the question and answer mode can make people better remember?)

catalogue

  • What is the default method?

  • Why provide a default implementation?

  • What if I don't provide it?

  • Who is this function mainly aimed at?

  • Is there any difference between an interface that implements the default method and an abstract class?

  • Is it possible to say that multiple inheritance is implemented?

text

What is the default method

The default method is the method decorated with default in the interface, which contains the method content

For example:

public interface InterfaceDemo {
    // Common method, only defined, not implemented
    void oldFun();
    // The default method is defined and implemented
    default void newFun(){
        System.out.println("newFun");
    }
}

Why provide a default method?

For backward compatibility (which is one of the reasons why Java becomes bloated).

When upgrading the system, it is inevitable that some new functions need to be added. At this time, if the interface class adds new methods, the implementation class must modify the implementation synchronously;

This is still a lot of work, and it is easy to make mistakes.

So Java 8 started to introduce the function of interface default method, which makes the interface upgrade more smooth

For example, the following code: InterfaceDemo is the interface above

public class UserDemo implements InterfaceDemo{
    @Override
    public void oldFun() {
        System.out.println("oldFun");
    }

    public static void main(String[] args) {
        UserDemo demo = new UserDemo();
        /**
         *  InterfaceDemo After upgrading, the newFun method is added
         *  However, because newFun is the default method, there are implementation contents
         *  Therefore, the subclass UserDemo here can be used directly
          */
        demo.newFun();
    }
}

We can see that UserDemo does not implement the new method newFun(), but it can also be compiled and run and directly call newFun()

This is the advantage of the default method: it is a painless upgrade for the implementation class

What if not?

If not, the system has two options when upgrading the interface class

  1. Implement class upgrade:
    • The implementation class honestly carries out synchronous modification and implementation according to the method after interface upgrade, but the workload is heavy
  2. Implementation class does not upgrade:
    • It's OK not to upgrade the implementation class. As long as the new version of the interface class is not introduced, the system can still run at this time, which is no problem. But who can guarantee that the system will not be updated for a lifetime? If the interface class library is upgraded to the new version when updating the system, the compilation will still fail

For whom?

The default method of interface is mainly for class library designers

Is there any difference between an interface that implements the default method and an abstract class

There are not as many differences as before, but there are still some:

  1. Single inheritance of abstract classes and multiple implementations of interface classes
  2. Initialization is not required when defining attributes in abstract classes. Initialization is required when defining attributes of interface classes (the default modifier is public static final)

Can it be said that Java now also implements multiple inheritance?

You can say so.

But now a new problem is the ambiguity caused by multiple inheritance, which is a bit similar to the deadly square (also known as the diamond problem) introduced before

As shown in the UML diagram below

For example, you can't know which interface fun method A will call

Therefore, the compiler will report an error:

com.jalon.java8.defaultmethod.A inherits unrelated defaults for fun() from types com.jalon.java8.defaultmethod.B and com.jalon.java8.defaultmethod.C

terms of settlement:

  • Override fun method first
  • The fun method that declares which interface to call is displayed again

The code is as follows:

public class A implements B,C{

    @Override
    public void fun(){
        // Displays the default method that calls B
        B.super.fun();
    }

    public static void main(String[] args) {
        A a = new A();
        // B's fun will be printed here
        a.fun();
    }
}
interface D{
    default void fun(){
        System.out.println("D");
    }
}
interface B extends D{
    @Override
    default void fun(){
        System.out.println("B");
    }
}
interface C extends D{
    @Override
    default void fun(){
        System.out.println("C");
    }
}

summary

  • What is the default method: the method decorated with default in the interface and containing the method content

  • Why provide default methods: backward compatibility to make the system transition smoothly; Mainly for class library designers

  • Problems brought by multiple inheritance: ambiguity, also known as diamond problem; The solution is that subclasses try to override the default method and explicitly declare which method to call (in fact, this problem rarely occurs, because it is a compilation error, which can be found at any time when writing code)

Postscript

Finally, thank you for watching, thank you

Wechat search [Tangyuan learning Java]:

  • Reply to [Java] get Java core books - electronic version for free
  • Reply to [Idea] and get Idea activation resources for free

Added by tomdelonge on Mon, 07 Mar 2022 23:06:11 +0200