我有两门课:
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/