Java 8 Default Method Example

Let’s understand why we need default methods which have been added in Java 8. Assume that we have an Interface with some abstract methods  and it has many implementation classes. Now if we want to add new method in the Interface it means we need to change all implementations.

Java 8 introduces new Default Methods which will allow us to add new methods without breaking all the existing implementations. (backwards compatibility)

For example List interface in Java 8 has the default method sort.

    @SuppressWarnings({"unchecked", "rawtypes"})
    default void sort(Comparator<? super E> c) {
        Object[] a = this.toArray();
        Arrays.sort(a, (Comparator) c);
        ListIterator i = this.listIterator();
        for (Object e : a) {
            i.next();
            i.set((E) e);
        }
    }

This method sorts this list according to the order induced by the specified Comparator.

We can add default methods to any interface.  If the class implements but doesn’t override the default method will get the default implementation.

For example:

public interface InterfaceExample {

    default int getX() {
        return 1;
    }
}

And the implementation class:

public class ImplExample implements InterfaceExample {

    public static void main(String[] args) {
        int x = new ImplExample().getX();
        System.out.println(x);
    }
}

So we can see that default method getX() can be used in the implementations.