简体   繁体   中英

Creating Immutable class in Java with mutable reference

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.

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 (ie, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM