我有两个不同的类,它们与一个私有字段具有相同的类。这个私有字段需要从一个类传递到另一个(或在另一个类中访问),但是我不确定如何。
这是我要执行的操作的一个示例:
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
}
}
为了使RealVector的距离方法起作用,需要将RealVector传递给它,但是Neuron的距离方法只有一个观察值传递给它,其中包含一个向量作为私有字段。我可以想到几种解决方法,但我并不真正喜欢它们。
1)进行观察和神经元扩展RealVector类。然后,我什至不必编写距离函数,因为它只使用超类(RealVector)距离方法。我真的不喜欢这种解决方案,因为观察者和Neuron与RealVector类具有“具有”关系,而不具有“是”关系。
2)在观察类中有一个返回RealVector的方法。
public RealVector getAttributes() {
return attributes;
}
我不喜欢这种解决方案,因为它违反了将RealVector字段设为私有的目的。在这种情况下,我不妨公开属性。
我可以让它在类中返回RealVector的(深层)副本。这种方法似乎效率低下,因为每次调用getAttributes()时,我都必须制作RealVector的副本(实质上是复制数组)。
3)使用界面。接口方面还没有做很多事情,所以我不太确定它们是否适合这里。
有谁知道我可以将属性保留为观察的私有成员并完成我要在Neuron的距离方法中进行的操作的方法吗?
最佳答案
如果您的Observer
类具有采用RealVector
的distance方法,则无需公开私有的RealVector attributes
。
public class Observation {
private RealVector attributes;
public double distance(RealVector weight){
return weight.distance(attributes);
}
}
public class Neuron {
private RealVector weight;
public double distance(Observation obs) {
return obs.distance(weight);
}
}
关于java - 访问Java中的通用类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12084012/