• Post Reply Bookmark Topic Watch Topic
  • New Topic

creating immutable class - does var need to be final?  RSS feed

 
Ags Karan
Greenhorn
Posts: 22
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,
I have seen the below code in one of the forums for creating immutable class , but I am doubted that the variables inside a class need to be final ? because final variables state can be changed and only they can't refer to some other object . If this understanding is correct then what is the significance of marking var final here ?



Thanks a lot in Advance.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Those are primitives so the value can't be changed. If there were an object like a StringBuilder, final would only protect the reference. IN other words, for a primitive, "final" really does make the variable immutable.

The class would still be immutable without the final keyword. Using final prevents a programmer from accidentally changing the instance variables in the future.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeanne Boyarsky wrote:The class would still be immutable without the final keyword. Using final prevents a programmer from accidentally changing the instance variables in the future.

And to make it really bullet-proof, I'd add final to your method declarations too ... although some might see that as overkill.

Basically, in order for a class to be immutable, it can't:
(a) Be generally subclassable. The normal (and simplest) way to do that is to make the class itself final, but there are other options.
(b) Have any public or protected methods that alter its state (eg, "setter" methods).
(c) Have any accessible data (ie, data obtainable via "getter" methods), that is not final and either primitive, immutable or a "safe copy".
(d) Allow any data to be supplied at construction time that is not either primitive, immutable or copied before storing.

All of which sounds like quite a mouthful; but my rule of thumb is just to slap 'final' on absolutely every possible thing I can.

Because you can always remove it if it's too much ... but you can't add it.

HIH

Winston
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!