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.
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.
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.