I want to have immutable Java objects like this (strongly simplyfied):
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?