gpt4 book ai didi

Java 8 错误 : Interface Inherits Abstract and Default

转载 作者:搜寻专家 更新时间:2023-10-30 21:09:46 27 4
gpt4 key购买 nike

我正在尝试编写一个集合接口(interface)库,该库使用 Java 8 中新的默认方法语法来实现标准集合 API 中的大部分方法。这是我要实现的目标的一个小示例:

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...
}

但是,即使是这个简单的示例也会遇到编译器错误:

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

根据我对默认方法的理解,这应该是允许的,因为只有一个扩展接口(interface)提供了默认实现,但显然情况并非如此。这里发生了什么?有没有办法让它做我想做的事?

最佳答案

这在 section 9.4.1.3 (Inheriting Methods with Override-Equivalent Signatures) 中有解释Java 语言规范:

It is possible for an interface to inherit several methods with override-equivalent signatures (§8.4.2).

...

Similarly, when an abstract and a default method with matching signatures are inherited, we produce an error. In this case, it would be possible to give priority to one or the other - perhaps we would assume that the default method provides a reasonable implementation for the abstract method, too. But this is risky, since other than the coincidental name and signature, we have no reason to believe that the default method behaves consistently with the abstract method's contract - the default method may not have even existed when the subinterface was originally developed. It is safer in this situation to ask the user to actively assert that the default implementation is appropriate (via an overriding declaration).

因为 MyCollectionList 都定义了一个方法 isEmpty() 并且一个是默认的,另一个是抽象的,编译器需要子接口(interface)以通过再次覆盖该方法来显式声明它应该继承哪一个。如果你想继承 MyCollection 的默认方法,那么你可以在覆盖实现中调用它:

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

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

如果你想让 MyList 保留 isEmpty() 抽象(我认为你不想要),你可以这样做:

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

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

关于Java 8 错误 : Interface Inherits Abstract and Default,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32753932/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com