我有一个接口(interface) Node 要求方法:
public HashSet getNeighbour();
NodeVariable 实现 Node,它的邻居是 NodeFunction 类型(也实现 Node),我编写了该方法:
public HashSet<NodeFunction> getNeighbour();
(在 NodeFunction 类中反之亦然)。
我发现如果我将 Node 中方法的签名更改为:
public HashSet<Node> getNeighbour();
然后在 NodeVariable 和 NodeFunction 中的方法上我收到错误:
Error getNeighbour() in factorgraph.NodeFunction cannot implement getNeighbour() in factorgraph.Node return type java.util.HashSet is not compatible with java.util.HashSet NodeFunction.java
这个还不太清楚。
我发现:
Overriding return type in extended interface - Bad idea?
和
现在我更改了 Node 方法签名:
public HashSet<? extends Node> getNeighbour();
因此编译器不再提示。
是吗?为什么 HashSet 不被视为 HashSet 的“扩展”?
最佳答案
首先,最好根据其他接口(interface)而不是具体实现来定义接口(interface)中的方法。我想说的是 getNeighbour()
方法应该是:
public Set getNeighbour();
既然我们知道它只能返回 Node(或 Node 的子类型),我们不妨这样定义它:
public Set<? extends Node> getNeighbour();
关于java - 扩展方法中的返回类型哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7867152/