繁体   English   中英

访问Java中的通用类

[英]Accesing a common class in Java

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

这是我要执行的操作的一个示例:

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);
    }   
}

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

关于

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

您应该理解,仅公开public getter不会损害字段的private属性,并且仅当不需要将其访问任何其他类时,一个属性才是真正的私有。

一种可能的方法是为类的私有变量引入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矢量字段,我认为您可以做的是为RealVector类的各个attributes使用getter/setter方法。 这样,您可以控制要从Observation类公开的内容。

暂无
暂无

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

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