问题
I've got a super-class (GraphNode) and sub-class (AStarNode). Both can be a member by another class thats why I turned the class which uses it into a generic class (GraphEdge).
Inside this class I'd like to call some member-functions of the super-class but the compiler complains that:
The method addEdge(GraphEdge<T>) is undefined for the type T
How can I fix this or is my approach even ok?
Here's some code that better describes the scenario:
public class GraphNode {
protected Graph graph;
public GraphEdge addEdge(){
//some code
}
}
public class AStarNode extends GraphNode {
protected GraphEdge predecessor;
}
//The from and to properties can be either AStarNode or GraphNode
public class GraphEdge<T> extends Entity {
protected T from;
protected T to;
public someMethod(){
from.addEdge(this);
}
}
回答1:
Your GraphEdge class uses a generic type which could be anything, and not just GraphNode. The declaration should be
public class GraphEdge<T extends GraphNode> extends Entity {
protected T from;
protected T to;
}
Additionally, since GraphEdge is a generic type, you should not use it as a raw type in AStarNode:
public class AStarNode extends GraphNode {
protected GraphEdge<PutSomeTypeHere> predecessor;
}
来源:https://stackoverflow.com/questions/10538774/calling-member-function-of-generic-member