DaLoverhino said:
String's are references, and so is MyClass, and Object, etc, etc.
If we are so worried about String's changing values underneath us, why
aren't we so worried about other references changing values underneath
us too?
You can control visibility of a particular reference, but not of objects
floating around in memory.
For example, if you declare a local variable inside a method, the only
thing that can modify what that variable points to is code inside the same
method. Assuming your code is no longer than 1 or 2 screenfulls, you don't
have to read much to know everything that's happening to the variable
itself.
However, anyone who has a reference to an object in memory can call the
methods on that object, possibly affecting its state.
As an example, consider this a method "void foo(Object bar)". Foo has
received a reference to an object which it stores in its variable bar. No
one can mess with what bar points to except the method itself; that is to
say, if foo never assigns anything else to bar, you can be confident that
bar will always point to the same object. But if bar points to a mutable
object, then anyone who has a reference to bar can change its state. And you
don't know who has a reference to bar. The method that called foo certainly
has a reference (how else could it have passed that reference to foo?), but
where did that method get its reference from? Perhaps it got it from yet
another method. And perhaps that method got it from a publically visible
field (meaning anyone at all can have access to the object).
A typical scenario where this issue comes up is when you have a
collection of something (e.g bank account information), and you want give
someone read-access to it, but not to give any write access. If you just
pass a vector of objects (even if it's a vector of immutable objects), then
client code could take that Vector and add or remove whatever it wants.
Since your code and the client code are sharing the same instance of the
Vector object, and changes the client makes will show up in your data!
- Oliver