为超类指定一个引用java

COM*_*COM 4 java inheritance reference superclass

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

Vector(int dimension) // creates a vector of size dimension
Run Code Online (Sandbox Code Playgroud)

我有一个类Neuron,它扩展了Vector类

public class Neuron extends Vector {

    public Neuron(int dimension, ... other parameters in here ...) { 
         super(dimension);
         // other assignments below here ...
     }    
}
Run Code Online (Sandbox Code Playgroud)

我希望能够做的是在Neuron类中为Vector指定另一个Vector的引用.有点像

    public Neuron(Vector v, ... other parameters in here ...) { 
         super = v;
         // other assignments below here ...
     }    
Run Code Online (Sandbox Code Playgroud)

当然,我不能这样做.有一些工作吗?即使我无法在Neuron类的构造函数中执行此操作,也许可以.

aio*_*obe 11

您需要在类中创建一个复制构造函数Vector:

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

    // ... copy other attributes
}
Run Code Online (Sandbox Code Playgroud)

然后在Neuron你做

public Neuron(Vector v, ... other parameters in here ...) { 
     super(v);
     // other assignments below here ...
}
Run Code Online (Sandbox Code Playgroud)

您也可以考虑使用合成而不是继承.实际上,这是Effective Java中的一个建议.在这种情况下你会这样做

class Neuron {
    Vector data;

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

相关问题: