Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning super class a reference java

I have a class Vector with a constructor

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

I have a class Neuron that extends the Vector class

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. 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.

like image 319
COM Avatar asked Dec 20 '22 18:12

COM


1 Answers

You need to create a copy constructor in the Vector class:

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

    // ... copy other attributes
}

and then in Neuron you do

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. 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:

  • Difference between Inheritance and Composition
  • Favor composition over inheritance
like image 127
aioobe Avatar answered Dec 24 '22 01:12

aioobe