调用通用成员的成员函数 [英] Calling member-function of generic member

查看:123
本文介绍了调用通用成员的成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



喜欢调用超类的某些成员函数,但编译器会抱怨:

 方法addEdge(GraphEdge< T> )是未定义的类型T 

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

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

  public class GraphNode { 
保护图表图形;
$ b $ public GraphEdge addEdge(){
//一些代码
}
}

公共类AStarNode扩展GraphNode {
受保护的GraphEdge前身;
}

// from和to属性可以是AStarNode或GraphNode
public class GraphEdge< T>扩展实体{
protected T from;
保护T到;

public someMethod(){
from.addEdge(this);
}

}


解决方案

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

  public class GraphEdge< T extends GraphNode>扩展实体{
protected T from;
保护T到;
}

另外,由于GraphEdge是一个泛型类型,因此您不应该将它用作AStarNode中的原始类型:

  public class AStarNode扩展GraphNode {
protected GraphEdge< PutSomeTypeHere>前任;
}


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

}

解决方案

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

这篇关于调用通用成员的成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆