簡體   English   中英

如何創建一個只能從它們的類中修改的公共靜態變量?

[英]How to create a public static variable that is modifiable only from their class?

我有兩個班級:

class a {
    public static int var;
    private int getVar() {
        return var; //Yes
    }
    private void setVar(int var) {
        a.var = var; //Yes
    }
}


class b {
    private int getVar() {
        return a.var; //Yes
    }
    private void setVar(int var) {
        a.var = var; //No
    }
}

問:我可以只從他的班級中創建可修改的成員,因為其他班級是不變的嗎?

不, public訪問修飾符基本上允許您從代碼庫中的任何位置修改引用的值。

您可以做的是根據您的特定需求擁有一個private或限制較少的訪問修飾符,然后實現一個 getter,但沒有 setter。

在后一種情況下,請記住添加一些邏輯以防止可變對象(例如集合)發生變異。

例子

class Foo {
    // primitive, immutable
    private int theInt = 42;
    public int getTheInt() {
        return theInt;
    }
    // Object, immutable
    private String theString = "42";
    public String getTheString() {
        return theString;
    }
    // mutable!
    private StringBuilder theSB = new StringBuilder("42");
    public StringBuilder getTheSB() {
        // wrapping around
        return new StringBuilder(theSB);
    }
    // mutable!
    // java 7+ diamond syntax here
    private Map<String, String> theMap = new HashMap<>();
    {
        theMap.put("the answer is", "42");
    }
    public Map<String, String> getTheMap() {
        // will throw UnsupportedOperationException if you 
        // attempt to mutate through the getter
        return Collections.unmodifiableMap(theMap);
    }
    // etc.
}

只需刪除setter並將變量setter private 那么其他類只能讀取 stetted 的值。

public class a {
 private static int var=2;
 public static int getVar() {
    return var; 
 }
}

但是當您使用Java reflection ,就沒有這樣的保護。

答案是否定的你不能讓一個公共靜態變量只從它的類中修改 你可以把變量設為私有並且只有公共 getter 或者你可以添加 setter私有

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM