0
votes

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.

1
just look at the String. You can´t modify it directly, any change made to an instance of a String does allways return a new instance of a String. You are not able to modify an instance of a String by just invoking methods on it.SomeJavaGuy

1 Answers

2
votes

Don't provide methods that modify the mutable objects

If you don't provide getters and if this instance was not passed to your class from an external source (usually passed to the constructor), then only your class has access to this composed instance.

Never store references to external, mutable objects passed to the constructor

In Java, even references are passed-by-value, so when a reference type is passed to the constructor of your class, you need to make a copy of the instance (i.e, don't use the instance that is passed, use a deep-copy of the instance).

create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

If you have to return reference types to your caller, then you should return defensive copies instead of references to original instances.