hmaheshwari hmaheshwari - 2 months ago 19
Java Question

Implementation of Immutable class in Java

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();
/* ... */
}

Answer

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

Comments