1

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.

1
  • 1
    Can you elaborate? Your desciption is self-contradicting. If it is an immutable class, there is no mutable variable inside. Commented May 5, 2011 at 8:21

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

One should also restrict inheritance. So, it is necessary to make the class final.
3
  1. Make the variable private
  2. Allow access to the fields of variable only via getters( getVarNameProperty1(), getVarNameProperty2() );
  3. Make class final in order to deny inheritance. In the child class one can create a public getter.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.