How to make a class immutable (like String)?

Questions by sha_kr2001   answers by sha_kr2001

Showing Answers 1 - 18 of 18 Answers

Dear Mr Tarun,

I dont  think that u have not understood the question.Immutable means when ever u will try to change the value of a string then a new object will be created  and will point to that new object not to the original one. Using final means that u r not allowing that class to extend...

satyd

  • Jan 11th, 2008
 

More drtails will be:-
 A class will be immutable if all of the following are true:

1)All of its fields are final
2)The class is declared final
3)The this reference is not allowed to escape during construction
4)Any fields that contain references to mutable objects, such as arrays, collections, or mutable classes like Date:
    -Are private
    -Are never returned or otherwise exposed to callers
    -Are the only reference to the objects that they reference
    -Do not change the state of the referenced objects after construction

  Was this answer useful?  Yes

Sarje

  • Aug 18th, 2009
 

immutable means once object is created then you can not make any change to it. if you try to do so then new object will be created and original object will be lost.
final modifier is used to indicate that the class can not be extended not to make any object immutable.
But if you make all of the instance fields final and once they are initialized through constructor they can not be changed. In this case you have to create each time a new object and your class object will be immutable.
 

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions