> Hi All,
> How can one make an object of user defined class
> immutable?
The simple answer is you can't. That is, you can't make the object itself immutable, but what you can do is make a wrapper so that the client never sees the object to begin with.
A classic example of a mutable class:
class MutableX {
private String name = "None";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I don't think it's possible to make this immutable, but you can create a wrapper that is:
class ImmutableX {
private final MutableX wrappedInstance;
public ImmutableX (String name) {
wrappedInstance = new MutableX();
wrappedInstance.setName(name);
}
public String getName() {
return wrappedInstance.getName();
}
// Don't give them a way to set the name and never expose wrappedInstance.
}
Of course, if you're asking how you can make your own class immutable then the simple answer is to not make any public or protected methods that can mutate it and don't expose any mutable members.
> Whats the implementation logic with strings as
> immutable?
>
> Regards,
I don't understand the question.