【问题标题】:List of inheriting objects javajava继承对象列表
【发布时间】:2021-01-28 17:31:10
【问题描述】:

我创建了一个小例子。假设我有两个类:

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
}

不能将 List(SpecialNeuron) 用于 List(Neuron) 参数。这个电话有什么问题,有没有合适的方法来解决这个问题? 此外,我可以做

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 类中的函数。

【问题讨论】:

  • 您必须将特定的 SpecialNeurons 从 Neuron 转换到该类,或者使用您在类 SpecialNeuron 中覆盖的所有神经元通用的方法。多态性会为你调用正确的版本。
  • @Jems 我在 Neuron 类中实现了空方法,这些方法将在 Special Neuron 类中被覆盖。由于多态性,它使我能够调用方法。感谢您的想法:)
  • 我是否应该删除这个问题,因为我似乎无法确定具体的解决方案而不是解决方法?

标签: java list inheritance


【解决方案1】:

您可以在通用&lt;? extends T&gt; 中使用通配符。您可以在here 阅读有关它的更多信息。

将您的方法参数更改为此。

  public void connect(ArrayList<? extends Neuron> directNeighbours) {
        for (Neuron node : directNeighbours) {
            this.neighbours.add(node);
        }
    }

【讨论】:

  • 非常有趣的功能。它适用于给定的示例,但不适用于我自己的项目。由于缺乏解释,我的错。
【解决方案2】:

首先,您正在扩展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&lt;SpecialNeuron&gt; special = new ArrayList&lt;&gt;(); - 你有 SpecialNeuron 对象列表,它们是 Neuron 类的子对象,所以 Java 知道它只包含类 SpecialNeuron 的对象

在您的connect() 函数中,您只接受Neuron 类对象,因此为了使其工作,您必须将您的special 列表更改为:

ArrayList<Neuron> special = new ArrayList<>();

在此列表中,您可以添加NeuronSpecialNeuron 对象并将其用作Neuron 对象的列表。

【讨论】:

  • 你是对的,但我无法解决该类独有的特殊神经元的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-23
  • 1970-01-01
  • 2011-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多