我有一个带有构造函数的类 Vector
Vector(int dimension) // creates a vector of size dimension
我有一个类 Neuron 扩展了 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 类的构造函数中执行此操作,也可能没问题。
最佳答案
您需要在 Vector
类中创建一个 copy constructor:
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 ...
}
}
相关问题: