What are mutable and immutable objects in Java?

John Mitchell

As per the dictionary, mutable objects are objects which can change their values and immutable objects are objects which cannot have their values changed.

The basic way to create an immutable object is to make all of its data fields private and don't create any methods which can change any of the data fields once the object has been constructed.

If you need to make an object immutable for which you don't control of the source code for its class, you can create a wrapper/adapter class which uses an instance of the existing, mutable class to do all of the work (via e.g., delagation) but doesn't provide any methods which can effect any change to the mutable object.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact