簡體   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