Consider this Java class:
public class Base {
private int a
protected int b;
public Base(int a,int b) {
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
}
...
Base foo = new Base(1,2);
Base bar = new Base(3,4);
There is no way(maybe except via dirty reflection) the foo
instance can change the protected or private variable in bar
You might allow it to if you want,
public class Base {
private int a
protected int b;
public Base(int a,int b) {
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
public void changeB(int newB,Base other) {
other.b = newB;
}
}
...
Base foo = new Base(1,2);
Base bar = new Base(3,4);
foo.changeB(5,bar);
You can't protect the changeB
method from altering stuff inside the other
object [*], you just have to be careful about what your program does. With some languages you could have marked the other
argument as unchangable , but not in Java - I don't find it a big deal.
[*} You could, by marking all the fields of Base
as final, though then not even the instance itself could change the members after the object has been constructed.