• Post Reply Bookmark Topic Watch Topic
  • New Topic

Making an existing class immutable  RSS feed

 
Pankaj Kumarkk
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would like to know how to make an existing 3rd party class immutable. I do not have the option of changing the source code of the class to make it immutable.
Thus how would clients of this class be given immutable version of this class.

I was asked this in an interview and do not much clue on the answer.
 
Luigi Plinge
Ranch Hand
Posts: 441
IntelliJ IDE Scala Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't make a class immutable; you'd have to create your own class.

You could extend the class and make all the setters do nothing, or throw an Exception. Unfortunately when extending a class you can only make the access modifiers less restrictive, so you can't hide the setters altogether by making them private.

Better might be to create a wrapper class, which just contains a private instance of the target class, and you duplicate the class's methods, except for the setters, by returning the result of the same method on the private instace. The disadvantage here is that your wrapper isn't actually the same class as your target, so it's not polymorphically the same, apart from if there are any interfaces that it's safe to implement.
 
Pankaj Kumarkk
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the explanation.

so you can't hide the setters altogether by making them private.

I didn't understand the above sentence. If i make the methods private then how can people access it still.

 
Luigi Plinge
Ranch Hand
Posts: 441
IntelliJ IDE Scala Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the class inherits a method public void setSomething(int v), you can't override this with private void setSomething(int v). It won't compile. However if were default or protected access before, you would be allowed make it public. It's just a result of subclasses polymorphically being their superclasses, so they have to be able to do everything the superclass can do, but it's OK to do more. You can also change behaviour, like making the setters do nothing, but you can't hide them.
 
Pankaj Kumarkk
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Understood. Thanks
 
Campbell Ritchie
Marshal
Posts: 56587
172
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I prefer LP's suggestion of a wrapper class. Make sure to declare the wrapper class final.
 
Manoj Kumar M
Greenhorn
Posts: 5
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I too prefer LP's solution is better.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!