[英]assigning super class a reference java
我有一个带有构造函数的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
类中创建一个复制构造函数 :
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 ...
}
}
相关问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.