You are confusing concepts, in your code the string variable "s" is immutable all along and in no moment it ceases to be immutable.
String s new String(); // Strings are ummutable
for x = 1 to 10
s = s + "z" // you are destroying an object, creating
// another one and assining it to the
// reference. You are not changing the
// internal state of the String.
s.Freeze() // It makes no sense. The only way to avoid
// assigning a new value to a variable is
// converting it into a constant. But then you can only
// assign an initial value when you declare it.
Immutability means not being able to alter the internal state of an object via properties, settters or methods.
In Java, the String class is immutable, meaning it has no setters or other method of changing its state.
The class StringBuffers is mutable, it has an Append()
method and others that change its internal state.
The String class being immutable doesn't mean you cannot over-write the a String object, and assing other string to the reference.
That being clear, you can certainly program a class whose setters raise and IllegalStateException
if you try to set a value after you have "frozen" it.
public class FreezableThing {
private String name="";
private int number=0;
boolean frozen = false;
public boolean isFrozen() { return frozen; }
public void setFrozen(boolean frozen) { this.frozen = frozen; }
public String getName() { return name; }
public int getNumber() { return number; }
public void setName(String name) {
if (this.frozen){
throw new IllegalStateException("Frozen object cannot be changed");
}
this.name = name;
}
public void setNumber(int number) {
if (this.frozen){
throw new IllegalStateException("Frozen object cannot be changed");
}
this.number = number;
}
}
...