java - 如何创建只能从其类修改的公共(public)静态变量?

标签 java class static member public

我有两门课:

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

关于java - 如何创建只能从其类修改的公共(public)静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31938120/

相关文章:

class - 在 Arduino 中使用类

c# - 静态变量如何在网络场中工作?

java - 如何使用模式匹配在某个字符之后获取字符串?

java - Android requestLocationUpdates 方法中的位置更新

android - 将值导入另一个类

c++ - 迭代 C++ 中的对列表?

java - 用一种方法创建一个类是否合适?

java - 将数组传递给 Activity (Android)

java - 自定义适配器 onClick 未注册点击

c++ - 类的成员复制