简体   繁体   中英

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

I have two classes:

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

Q: Can i make modifiable member only from his class, for other classes would be constant ?

No, the public access modifier basically allows you to modify the value of the reference from anywhere in your code base.

What you can do is have a private or less-restricted access modifier according to your specific needs, and then implement a getter, but no setter.

In the latter case, remember to add some logic to prevent mutable objects, such as collections, from being mutated.

Example

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.
}

Just remove setter and make variable private . Then other class only can read the value stetted.

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

But when you come to Java reflection there is no such protection.

答案是否定的你不能让一个公共静态变量只从它的类中修改 你可以把变量设为私有并且只有公共 getter 或者你可以添加 setter私有

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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