【问题标题】:Calling member-function of generic member调用泛型成员的成员函数
【发布时间】:2012-05-10 16:52:55
【问题描述】:

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

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

The method addEdge(GraphEdge<T>) is undefined for the type T

我该如何解决这个问题,或者我的方法还可以吗?

这里有一些代码可以更好地描述场景:

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

}

【问题讨论】:

  • 为确保我们都在谈论同一件事,请发布一个简短的代码 sn-p 来说明您的类之间的关系。
  • 我添加了一些代码来描述场景。

标签: java generics inheritance


【解决方案1】:

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

public class GraphEdge<T extends GraphNode> extends Entity {
   protected T from;
   protected T to;
}

另外,由于 GraphEdge 是泛型类型,你不应该在 AStarNode 中将其用作原始类型:

public class AStarNode extends GraphNode {
    protected GraphEdge<PutSomeTypeHere> predecessor;
}

【讨论】:

  • 谢谢,只有 52 个零件需要参数化,但这很好。您如何看待我的方法?有更好的吗?
  • 在不了解这些类的用途、它们代表什么以及如何使用它们的情况下很难说。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-29
  • 1970-01-01
  • 2011-06-04
相关资源
最近更新 更多