我创建了一个小示例。假设我有两个类:
public class Neuron {
ArrayList<Neuron> neighbours = new ArrayList<>();
int value = 1;
public Neuron() {
}
public void connect(ArrayList<Neuron> directNeighbours) {
for (Neuron node : directNeighbours) {
this.neighbours.add(node);
}
}
}和一个继承自Neuron的类:
public class SpecialNeuron extends Neuron {
int value = 2;
public SpecialNeuron() {
}
}在我的例子中,我想要继承,以避免许多“如果对象是特殊的做一些事情”的东西。但是,当我呼叫时:
public static void main(String[] args) {
ArrayList<Neuron> neurons = new ArrayList<>();
Neuron a = new Neuron();
Neuron b = new Neuron();
Neuron c = new Neuron();
neurons.add(b);
neurons.add(c);
a.connect(neurons);
ArrayList<SpecialNeuron> special = new ArrayList<>();
SpecialNeuron d = new SpecialNeuron();
SpecialNeuron e = new SpecialNeuron();
special.add(d);
special.add(e);
a.connect(special); //Error
}不能将列表(SpecialNeuron)用于列表(神经元)参数。这个调用有什么问题,有没有合适的方法来解决这个问题?此外,我还可以
ArrayList<Neuron> special = new ArrayList<>();
Neuron d = new SpecialNeuron();
Neuron e = new SpecialNeuron();
special.add(d);
special.add(e);
a.connect(special); //works fine它可以工作,但拒绝使用SpecialNeuron类中的任何函数。
发布于 2021-01-29 01:50:54
您可以在Generic <? extends T>中使用WildCards,.You可以阅读有关它的更多信息here。
将你的方法参数改成这样。
public void connect(ArrayList<? extends Neuron> directNeighbours) {
for (Neuron node : directNeighbours) {
this.neighbours.add(node);
}
}发布于 2021-01-29 01:48:26
首先,您正在扩展Neuron类,但是您并没有真正使用继承。您应该使value变量为protected,并在构造函数中设置它的值。
public class Neuron {
protected int value;
public Neuron() {
this.value = 1;
}
}
public class SpecialNeuron extends Neuron {
public SpecialNeuron() {
this.value = 2;
}
}现在,您的问题出现在第17 - ArrayList<SpecialNeuron> special = new ArrayList<>();行-您有SpecialNeuron对象的列表,这些对象是Neuron类的子类,所以ArrayList<SpecialNeuron> special = new ArrayList<>();知道它只包含类SpecialNeuron的对象
在您的connect()函数中,您只接受Neuron类对象,因此为了使其正常工作,您必须将special列表更改为:
ArrayList<Neuron> special = new ArrayList<>();在此列表中,您可以添加Neuron和SpecialNeuron对象,并将其用作Neuron对象的列表。
https://stackoverflow.com/questions/65942283
复制相似问题