[英]generic abstract class constructor
I'm trying to call a constructor for a generic abstract class within a method of said class. 我正在尝试在所述类的方法内为通用抽象类调用构造函数。 The code below shows this:
下面的代码显示了这一点:
public abstract class Node<T> {
public Collection <Node<T>> pars;
public Collection<Node<T>> interactors;
private boolean target = false;
private boolean multiple = false;
private T value;
//constructor for a simple node
public Node(T val){
this.value = val;
}
//constructor for a multiple interaction node
public Node(Collection<Node<T>> inter, T val){
this.interactors = inter;
this.value = val;
if (inter.size()>0){
this.multiple = true;
}
}
public void find_inters(){
ArrayList<Collection<T>> multi_interactions = search();
for (int i = 0; i < multi_interactions.size(); i++){
Node<T> a = new Node<T>(multi_interactions.get(i), this.value); <----i get compile error here
}
}
}
but I keep getting an error that I can't instantiate type Node. 但我不断收到错误消息,无法实例化Node类型。 I want to create a new Node object within the function find_inters() but I can't.
我想在函数find_inters()中创建一个新的Node对象,但是我不能。 Anyone know why/possible solutions?
有人知道为什么/可能的解决方案吗?
You've said that Node
is abstract because you can't yet implement some of the methods, but the problem is that you want Node<T> a
to be a Node
object, but you have to decide what a
will actually do when you call those methods. 您已经说过
Node
是抽象的,因为您还不能实现某些方法,但是问题是您希望Node<T> a
成为Node
对象,但是您必须决定当a
实际执行什么操作时调用那些方法。
You can have classes that don't have all their methods implemented -- that's how abstract
classes work -- but you can't have objects that don't have all their methods implemented, because that object can have that method called, and your program needs to know what to do. 你可以没有实现其所有方法的类-这是多么
abstract
类的工作-但你不能没有他们所有的方法实现的对象 ,因为对象可以有人称这种方法,你的程序需要知道该怎么做。
What you can do is write Node<T> a = new MySubNode<T>(...)
, where MySubNode
is a subclass of Node
with all the methods filled in. Or you can write Node<T> a = new Node<T>(...) { implementations of methods go here }
, which is essentially the same thing, except the implementation is in an anonymous class. 您可以执行以下操作:写
Node<T> a = new MySubNode<T>(...)
,其中MySubNode
是Node
的子类,并填充了所有方法。或者您可以编写Node<T> a = new Node<T>(...) { implementations of methods go here }
,除了实现是在匿名类中之外,这基本上是相同的。 But you can't instantiate an abstract class. 但是您不能实例化一个抽象类。
Just to add to Louis's answer. 只是为了增加路易斯的答案。 If
search()
is abstract, you can change it to return ArrayList<Node<T>>
, so the implementing classes can do something like Node<T> a = new MySubNode<T>(...)
(unless search() is used somewhere else that requires ArrayList<Collection<T>>
). 如果
search()
是抽象的,则可以将其更改为返回ArrayList<Node<T>>
,因此实现类可以执行类似于Node<T> a = new MySubNode<T>(...)
(除非search()在需要ArrayList<Collection<T>>
其他地方使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.