Are conflict resolution sub-interfaces the default?

Consider the following code, which is the extraction of a real use case, where it LinkedList<E>implements both List<E>, and Deque<E>.

You may notice that both interfaces have a method size()and isEmpty()where the method isEmpty()can be set by default in terms of size().

So, let this (with dummy interfaces) since Java 8 does not do this yet:

interface List<E> {
    public int size();

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

    //more list operations
}

interface Deque<E> {
    public int size();

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

    //more deque operations
}

class LinkedList<E> implements List<E>, Deque<E> {
    private int size;

    @Override
    public int size() {
        return size;
    }
}

Oops! We get a compile-time error on LinkedList, because it does not know which implementation to isEmpty()use, so we add the following:

@Override
public boolean isEmpty() {
    return List.super.isEmpty();
}

, - , isEmpty(), .

? !

:

interface Sizable {
    public int size();

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

interface List<E> extends Sizable {
    //list operations
}

interface Deque<E> extends Sizable {
    //deque operations
}

class LinkedList<E> implements List<E>, Deque<E> {
    private int size;

    @Override
    public int size() {
        return size;
    }
}

, :

  • , JDK, ?
+4
1

- default. , , , - Collection, default. , class , , , .

API Collection, default isEmpty, , size Collection s. Collection Collection, AbstractCollection.

+4

Source: https://habr.com/ru/post/1535431/


All Articles