简体   繁体   English

为超类指定一个引用java

[英]assigning super class a reference java

I have a class Vector with a constructor 我有一个带有构造函数的Vector类

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

I have a class Neuron that extends the Vector class 我有一个类Neuron,它扩展了Vector类

public class Neuron extends Vector {

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

What I want to be able to do is assign the Vector in the Neuron class a reference to another Vector. 我希望能够做的是在Neuron类中为Vector指定另一个Vector的引用。 Something along the lines of 有点像

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

Of course, I can't do this. 当然,我不能这样做。 Is there some work around? 有一些工作吗? Even if I was not able to do this in the constructor of the Neuron class, that would probably be OK. 即使我无法在Neuron类的构造函数中执行此操作,也许可以。

You need to create a copy constructor in the Vector class: 您需要在Vector类中创建一个复制构造函数

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

    // ... copy other attributes
}

and then in Neuron you do 然后在Neuron你做

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

You may also consider using on composition instead of inheritance . 您也可以考虑使用合成而不是继承 In fact, that is one of the recommendations in Effective Java. 实际上,这是Effective Java中的一个建议。 In such case you would do 在这种情况下你会这样做

class Neuron {
    Vector data;

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

Related questions: 相关问题:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM