Fundamentals

Default Methods

Collections

Idioms and Techniques

Design Rationale

Advanced Questions

Do default methods introduce multiple inheritance to Java?

No, because multiple inheritance is already present in Java. Multiple inheritance of interface types has been a feature of the language since its beginning. Default methods do introduce a new kind of multiple inheritance, namely multiple inheritance of behaviour. Java will still not have multiple inheritance of state, as for example C++ has.

Here is an example of multiple inheritance of behaviour. The new interface java.util.Sized declares methods size and isEmpty and provides a default implementation of the latter:

    public interface Sized { 
        public default boolean isEmpty() { 
            return size() == 0; 
        } 
        public int size(); 
    } 

The new interface java.util.Traversable<T> declares the method forEach and provides a default implementation:

    public interface Traversable<T> { 
        public default void forEach(Block<? super T> block) { 
            for (T t : this) { 
                block.apply(t); 
            } 
        } 
    } 

Suppose we now declare a class SimpleCollection<T> and provide it with implementations of iterator and size:

    class SimpleCollection<T> implements Sized, Traversable<T> { 
        public Iterator<T> iterator() { ... } 
        public int size() { ... } 
    } 

then, given a declaration

    SimpleCollection<String> sc = new SimpleCollection<>();

the following statements all compile:

    Sized s = sc;                        // SimpleCollection is a subtype of Sized 
    Traversable<String> t = sc;          // SimpleCollection is a subtype of Traversable 
    System.out.println(sc.isEmpty());    // Default implementation of isEmpty available from Sized 
    sc.forEach(System.out::println);     // Default implementation of forEach available from Traversable 

interface java.util.functions.Block{ void apply(T t); }