How can 1 make an object of user defined class immutable?

Hi All,How can one make an object of user defined class immutable?Whats the implementation logic with strings as immutable?Regards,
[159 byte] By [chinnionlinea] at [2007-10-2 6:39:26]
# 1
if there's no way to change the state of the object, then it's immutable.that means all final data members and no methods that change state once it's set.%
duffymoa at 2007-7-16 13:47:37 > top of Java-index,Java Essentials,Java Programming...
# 2

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

kablaira at 2007-7-16 13:47:37 > top of Java-index,Java Essentials,Java Programming...
# 3
> Whats the implementation logic with strings as> immutable?Same way as others have already described for your own classes: No setter methods or non-final member variables.
targaryena at 2007-7-16 13:47:37 > top of Java-index,Java Essentials,Java Programming...