I am writing a immutable class.One of the instance is an object of another class which is mutable.How can i prevent the modification of the state of that instance.
2 Answers
If you provide delegates to all the getters, but don't provide a getter for the field itself. For example:
public final class Foo {
private Bar bar;
public String getBarField1() {
return bar.getBarField1();
}
public String getBarField2() {
return bar.getBarField2();
}
}
But there is a thing to consider - how is the field created. If it is passed in constructor, then you have to create a copy of it rather than get the passed object, otherwise the creating code will have reference to the Bar instance and be able to modify it.
1 Comment
Vladimir Ivanov
One should also restrict inheritance. So, it is necessary to make the class final.
- Make the variable private
- Allow access to the fields of variable only via getters(
getVarNameProperty1(),getVarNameProperty2()); - Make class final in order to deny inheritance. In the child class one can create a public getter.
1 Comment
Alan Escreet
You can't allow access to the variables with getters. The getters will return references to the variables that will allow the internal state of the immutable to be changed. The variables will have to be internally locked down.