Calling member-function of generic member

独自空忆成欢 提交于 2019-12-24 03:29:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!