调用泛型成员的成员函数

Hed*_*dge 2 java generics inheritance

我有一个超类(GraphNode)和子类(AStarNode).两者都可以是另一个类的成员,这就是为什么我将使用它的类转换为泛型类(GraphEdge).

在这个类中,我想调用超类的一些成员函数,但编译器抱怨:

The method addEdge(GraphEdge<T>) is undefined for the type T
Run Code Online (Sandbox Code Playgroud)

我怎么能解决这个问题,或者我的方法是否正常?

以下是一些更好地描述场景的代码:

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);
   } 

}
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 6

您的GraphEdge类使用的泛型类型可以是任何东西,而不仅仅是GraphNode.声明应该是

public class GraphEdge<T extends GraphNode> extends Entity {
   protected T from;
   protected T to;
}
Run Code Online (Sandbox Code Playgroud)

此外,由于GraphEdge是泛型类型,因此不应将其用作AStarNode中的原始类型:

public class AStarNode extends GraphNode {
    protected GraphEdge<PutSomeTypeHere> predecessor;
}
Run Code Online (Sandbox Code Playgroud)