Immutable Classes and Objects in java

If the content of an object is unchangeable once the object is created, such object is known as immutable object and its class is known as immutable class.

Immutable Class

Immutable Class

To design immutable class, make all data fields private and don’t write any mutator method (use to set data fields ) or any accessor method ( use to access values from data fields) that return any object that returns a reference to a mutable data field object. Consider the following example of immutable classes.

Another example with private data fields and without mutator methods, but class is still mutable.

Mutable Class

Mutable Class


 

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.