I have two different classes that have the same class as a private field. This private field needs to be passed from one class to the other (or accessed in the other class), but I’m not sure how.
Here’s an example of what I am trying to do:
public class RealVector() {
private double[] components;
// Other fields and methods in here
public double distance(RealVector vec) {
// Some code in here
}
}
public class Observation() {
private RealVector attributes;
// Other fields and methods in here
}
public class Neuron() {
private RealVector weight;
// Other fields and methods in here
public double distance(Observation obs) {
return weight.distance(obs.attributes); // This is what I want to do, but it won't work, since attributes is private
}
}
For the distance method of RealVector to work it needs a RealVector passed to it, but the distance method of Neuron only has an Observation passed to it, which contains a vector as a private field. I can think of a couple of workarounds, but I don’t really like them.
1) Make Observation and Neuron extend the RealVector class. Then I wouldn’t even have to write a distance function since it would just use the superclass (RealVector) distance method. I don’t really like this solution since Observation and Neuron have a “has a” relation with the RealVector class and not an “is a” relation.
2) Have a method in the Observation class that returns the RealVector.
public RealVector getAttributes() {
return attributes;
}
I don’t like this solution, since it defeats the purpose of having the RealVector field private. I might as well make attributes public in this case.
I could have it return a (deep) copy of the RealVector in the class. This approach seems inefficient, since I would have to make a copy of the RealVector (essentially copy an array) every time I call getAttributes().
3) Use interfaces. Haven’t done much with interfaces, so I’m not too sure if they would be appropriate here.
Does anyone know of a way that I can keep attributes as a private member of Observation and accomplish what I’m looking to do in the distance method of Neuron?
If your
Observerclass has a distance method which takes in aRealVectorthen you don’t need to expose the privateRealVector attributes.