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);
}
}
interface Deque<E> {
public int size();
default public boolean isEmpty() {
return (size() == 0);
}
}
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 {
}
interface Deque<E> extends Sizable {
}
class LinkedList<E> implements List<E>, Deque<E> {
private int size;
@Override
public int size() {
return size;
}
}
, :