Java 8 error: interface inherits abstraction and default

I'm trying to write a collection interface library using the new default method syntax in Java 8 to implement most of the methods in the standard collection API Here is a small sample I want to make:

public interface MyCollection<E> extends Collection<E> {
    @Override default boolean isEmpty() {
        return !iterator().hasNext();
    }
    //provide more default overrides below...
}

public interface MyList<E> extends MyCollection<E>,List<E> {
    @Override default Iterator<E>iterator(){
        return listIterator();
    }
    //provide more list-specific default overrides below...
}

However, even this simple example encountered a compilation error:

error: interface MyList<E> inherits abstract and default
       for isEmpty() from types MyCollection and List

From my understanding of the default method, this should be allowed because only one extension interface provides the default implementation, but obviously not What happened here? Is there any way to get what I want?

Solution

This is in section 9.4 of the Java language specification It is explained in 1.3 (inheriting methods with override equivalent signatures):

Therefore, since both mycollection and list define a method isempty (), one is the default method and the other is abstract, the compiler needs a sub interface to override the method again to explicitly declare which method it should inherit If you want to inherit the default method of MyCollection, you can call it in the implementation of rewrite:

public interface MyList<E> extends MyCollection<E>,List<E> {
    @Override default boolean isEmpty() {
        return MyCollection.super.isEmpty();
    }

    @Override default Iterator<E> iterator(){
        return listIterator();
    }
    ...
}

If you want mylist to keep isempty () Abstract (I don't think you want it), you can do this:

public interface MyList<E> extends MyCollection<E>,List<E> {
    @Override boolean isEmpty();

    @Override default Iterator<E> iterator(){
        return listIterator();
    }
    ...
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>