I have an interface Node that asks for the method:
public HashSet getNeighbour();
NodeVariable implements Node, and its neighbours are of type NodeFunction (that implements Node, too), and I wrote the method:
public HashSet<NodeFunction> getNeighbour();
(and viceversa in NodeFunction class).
I found out that if I change the signature of method in Node to:
public HashSet<Node> getNeighbour();
then on the methods in NodeVariable and NodeFunction I get the error:
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
This is not really clear.
I found:
Overriding return type in extended interface – Bad idea?
and
and now I changed the Node method signature in:
public HashSet<? extends Node> getNeighbour();
thus the compiler stops complaining.
Is it right? Why HashSet is not considered like an “extension” of HashSet?
HashSet<Node>andHashSet<NodeFunction>aren’t compatible, even thoughNodeFunctionimplements/subclassesNode. Similarly, neither areList<Number>andList<Integer>.IntegersubclassesNumber.If the compiler allowed what your trying to do, then I could do the following and a
ClassCastExceptionwould be thrown, which is the exact reason generics was created.Everything is semantically/syntactically valid except
public Set<NodeFunction> getNeighbour(){}. The Java tutorials cover this issue.