gpt4 book ai didi

java - 为父类(super class)分配一个引用java

转载 作者:搜寻专家 更新时间:2023-11-01 01:22:49 25 4
gpt4 key购买 nike

我有一个带有构造函数的 Vector 类

Vector(int dimension) // creates a vector of size dimension

我有一个扩展 Vector 类的神经元类

public class Neuron extends Vector {

public Neuron(int dimension, ... other parameters in here ...) {
super(dimension);
// other assignments below here ...
}
}

我想要做的是将 Neuron 类中的 Vector 分配给另一个 Vector 的引用。类似

的东西
    public Neuron(Vector v, ... other parameters in here ...) { 
super = v;
// other assignments below here ...
}

当然,我不能这样做。有一些解决方法吗?即使我无法在 Neuron 类的构造函数中执行此操作,也可能没问题。

最佳答案

您需要创建一个 copy constructorVector 类中:

public Vector(Vector toCopy) {
this.dimension = toCopy.dimension;

// ... copy other attributes
}

然后在 Neuron 中做

public Neuron(Vector v, ... other parameters in here ...) { 
super(v);
// other assignments below here ...
}

您也可以考虑使用组合 而不是继承。事实上,这是 Effective Java 中的建议之一。在这种情况下你会做

class Neuron {
Vector data;

public Neuron(Vector v, ... other parameters in here ...) {
data = v;
// other assignments below here ...
}
}

相关问题:

关于java - 为父类(super class)分配一个引用java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11672737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com