Interface default methods versus static methods

In some cases, if an interface adds a method, all the interface implementation classes need to implement it, and some implementation classes need to write an empty implementation without implementing the method at all, so the interface default method is designed to solve this problem.

Interface static methods are similar to default methods, but we cannot override them in the implementation class to avoid overwriting the default methods in the implementation class.

The list. Foreache method in JDK8 is the default method in java.lang.Iterable.

default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); }}Copy the code

Simple example

The default method is decorated with default, and the static method is static.

public static void main(String[] args) {
    IUserInterface userInterface = new UserServiceImpl();
    System.out.println(userInterface.getDefaultUser1());
    System.out.println(IUserInterface.getDefaultUser2());
}

interface IUserInterface {

    default User getDefaultUser1() {
        return new User("Susan1", 11);
    }

    static User getDefaultUser2() {
        return new User("Susan2", 22);
    }

}

static class UserServiceImpl implements IUserInterface {

}
Copy the code

Pay attention to the point

1, interface default method, static method can have more than one.

2. The default method is called by instance, and the static method is called by interface name.

The keyword can only be used in interfaces.

4. The default method can be inherited. If multiple interfaces are inherited, the implementation class needs to override the default method or an error will be reported.

Static methods cannot be inherited or overridden, so they are called only by the specified interface.

Recommended reading

Dry goods: Free 2TB architect four-stage video tutorial

Interview: the most complete Java multithreaded interview questions and answers

Tools: Recommended an online creation flow chart, mind mapping software

Share Java dry goods, high concurrency programming, hot technology tutorials, microservices and distributed technology, architecture design, blockchain technology, artificial intelligence, big data, Java interview questions, and cutting-edge hot news.