I want to have immutable Java objects like this (strongly simplified):
class Immutable {
protected String name;
public Immutable(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
In some cases the object should not only be readable but mutable, so I could add mutability through inheritance:
public class Mutable extends Immutable {
public Mutable(String name) {
super(name);
}
public void setName(String name) {
super.name = name;
}
}
While this is technically fine, I wonder if it conforms with OOP and inheritance that mutable is also of type immutable. I want to avoid the OOP crime to throw UnsupportedOperationException for immutable object, like the Java collections API does.
What do you think? Any other ideas?
Avoid calling the parent “Immutable” because it becomes a lie in the child class – if you do want to make a class immutable, it should be final too in order to prevent exactly this problem.
Joda Time uses “ReadableXXX” to give the idea that “this class only provides read access; other subclasses may be mutable”. I’m not sure whether I like that idea, but I can’t say I’ve seen many alternatives.
Basically the problem is with expressing a negative –
Immutabledescribes what you can’t do (mutate it) and that can’t be sensibly enforced in subclasses. (Even if the fields withinImmutablewere final, it wouldn’t stop a subclass having its own mutable fields.)