访问Java中的公共类

时间:2012-08-23 02:36:21

标签: java inheritance private-members

我有两个不同的类,它们与私有字段具有相同的类。这个私有字段需要从一个类传递到另一个类(或在另一个类中访问),但我不确定如何。

这是我想要做的一个例子:

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,但是神经元的距离方法只有一个观察传递给它,它包含一个向量作为私有字段。我可以想到几个解决方法,但我并不喜欢它们。

1)使Observation和Neuron扩展RealVector类。然后我甚至不必编写距离函数,因为它只使用超类(RealVector)距离方法。我不太喜欢这个解决方案,因为Observation和Neuron与RealVector类有一个“有”关系,而不是“是一种”关系。

2)在Observation类中有一个返回RealVector的方法。

public RealVector getAttributes() {
    return attributes;
}  

我不喜欢这个解决方案,因为它违背了将RealVector字段设为私有的目的。在这种情况下,我不妨公开属性。

我可以让它返回类中RealVector的(深层)副本。这种方法似乎效率低下,因为每次调用getAttributes()时我都必须复制一个RealVector(本质上是复制一个数组)。

3)使用接口。没有做太多的接口,所以我不太确定它们是否合适。

有没有人知道我可以将属性保存为观察的私人成员,并完成我在神经元的距离方法中要做的事情?

3 个答案:

答案 0 :(得分:1)

如果您的Observer班级的距离方法有RealVector,则您无需公开私有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);
    }   
}

答案 1 :(得分:0)

执行此操作的标准方法是保留字段private并创建public getXXX()setXXX()方法。

关于

  

我不喜欢这个解决方案,因为它违背了将RealVector字段设为私有的目的。在这种情况下,我不妨公开属性。

你应该明白,暴露公共getter并不会损害字段的private属性,只有当不需要访问任何其他类时,一个属性才真正是私有的。

答案 2 :(得分:0)

一种可能的方法是为类的私有变量引入getter/setter方法。例如,对于Observation类,您可以按如下方式修改它:

public class Observation() {

    private RealVector attributes;

    public RealVector getAttributes(){
        return attributes;
    }

    public RealVector setAttributes(RealVector attributes){
        this.attributes = attributes;
    }

    // Other fields and methods in here
}

编辑您的问题对我错过的getter/setters有以下评论:

  

我不喜欢这个解决方案,因为它违背了拥有该解决方案的目的   RealVector字段私有。我不妨公开属性   这种情况。

如果您确实不想公开RealVector向量字段,我认为您可以为getter/setter类的attributes个人提供RealVector方法。通过这种方式,您可以控制要从Observation课程中公开的内容。

相关问题