Search code examples
javaclassstaticmemberpublic

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 ?


Solution

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