0

In my application, I need to make my class as immutable, but in my class I have an object of other class which is mutable, can anyone please suggest me Implementation.

Pseudo code:

Class A which I would like as immutable class

class A {
    /* ... */ 

    //class B is mutable
    B b = new B();
    /* ... */ 
}
2
  • Make b private inside the instance Commented Sep 6, 2016 at 19:58
  • ... and final Commented Sep 6, 2016 at 20:00

1 Answer 1

2

Assuming you need to access b from outside world, you will need to wrap all methods on B and declare those in A. Additionally, take b as constructor parameter, without getter/setter method.

class A{
   private final b;
   A(B b){
     this.b = b;    
   }
   public String getSomeValue(){
     return b.getSomeValue();
   }

}

Edit: Refer to Hoopje' comment regarding cloning b in constructor. If clone or copy constructor not available on B then you have to construct new B on your own in A

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

2 Comments

You should make a copy of b in the constructor. Now, you can save a reference to the B object elsewhere and change the object after creating the A object, thus changing the immutable A object.
additionally, make your class final to prohibit inheritance

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.