• Post Reply Bookmark Topic Watch Topic
  • New Topic

Final class and immutability  RSS feed

 
Larsen Raja
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Will all the classes declared with the keyword 'final' go immutable? (Just like String class and wrapper classes.)


Larsen.
 
Paul Clapham
Sheriff
Posts: 22713
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. Declaring a class "final" just says it can't be overridden. That doesn't affect its mutability in any way.
 
karthick chinnathambi
Ranch Hand
Posts: 196
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want a class to be immutable you have to make all it's instance variables private and you shouldn't provide any setter methods that manipulate those instance variables. The classes can be made immutable by implementing it in such a way . Not by adding specifiers.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16048
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to make a class immutable, then one of the things you should do is make the class final.

But, as others have already said, making a class final does not make the class immutable (it's a necessary, but not a sufficient condition).
 
naveen yadav
Ranch Hand
Posts: 384
Java MyEclipse IDE Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Apart from declaring the class FINAl in order to make class immutable one must take care of two more things(as far as i know)

1). make fields of class PRIVATE and FINAL.
2). there must not any kind of setter method which may change or modify the state of object.

but i think something more is there to make class immutable.

Let say i want to create a immutable class , Immune , from above points.



i know its not immutable how can i create one ?
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
naveen yadav wrote:i know its not immutable

What makes you think it's not immutable ?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!