I didn't understand the requirement to make a class immutable in Java. Following is the requirement which I am not able to understand:
1) If the instance fields include references to mutable objects, don't allow those objects to be changed:
a) Don't provide methods that modify the mutable objects.
b) Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
Please explain this concept with a clear and simple example.
String
. You can´t modify it directly, any change made to an instance of aString
does allways return a new instance of aString
. You are not able to modify an instance of aString
by just invoking methods on it. – SomeJavaGuy