Reputation: 5137
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.
Upvotes: 1
Views: 120
Reputation: 43108
getVarNameProperty1()
, getVarNameProperty2()
);Upvotes: 3
Reputation: 597422
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.
Upvotes: 5