Search

Interface improvements

Interface improvements
Interfaces can now define static methods. For example, java.util.Comparator now has a static naturalOrder method.

 public static <T extends Comparable<? super T>> Comparator<T> naturalOrder() {
        return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE;
    }

Interfaces can now provide default methods. This allows programmers to add new methods without breaking existing code that implements the interface. For example, java.lang.Iterable now has a default forEach method.
    public default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }
Note that an interface cannot provide a default implementation for any of the methods of the Object class.

Functional interfaces

A functional interface is an interface that defines exactly one abstract method. TheFunctionalInterface annotation has been introduced to indicate that an interface is intended to be a functional interface. For example, java.lang.Runnable is a functional interface.
    @FunctionalInterface
    public interface Runnable {
        public abstract void run();
    }
Note that the Java compiler will treat any interface meeting the definition as a functional interface regardless of whether or not the FunctionalInterface annotation is present.

No comments:

Post a Comment