hmaheshwari hmaheshwari - 1 year ago 85
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:


which I would like as immutable class

class A {
/* ... */

//class B is mutable
B b = new B();
/* ... */

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download