Do you know how can I make an object changeable only inside a special class?
In this example I want the object PrivateObject to be only changable (incrementable) inside the Box class, nowhere else. Is there a way to achieve this?
public class Box {
private PrivateObject prv;
public void setPrivateObject(PrivateObject p){
prv = p;
}
public void changeValue(){
prv.increment();
}
}
public class PrivateObject {
private value;
public increment(){
value++;
}
}
PrivateObject priv = new PrivateObject ();
Box box = new Box();
box.setPPrivateObject(priv);
box.changevalue();
priv.increment(); // I don't want it to be changeable outside the Box class!
In C++, I would make all the PrivateObject properties and methods private, and the declare the Box class as a friend for the PrivateObject class.
解决方案
If PrivateObject is strongly related to Box why not make it an inner class inside Box?
class Box {
public static class PrivateObject {
private value;
private increment(){
value++;
}
}
private PrivateObject prv;
public void setPrivateObject(PrivateObject p){
prv = p;
}
public void changeValue(){
prv.increment();
}
}
Now you cannot call increment from outside Box:
public static void main(String args[]) {
Box.PrivateObject obj = new Box.PrivateObject();
Box b = new Box();
b.setPrivateObject(obj);
obj.increment(); // not visible
}