Here is an example of an immutable class:
package com.immutable;
public final class ImmutableClass {
private final int index;
private final String tStr;
private final ComplexObj cObj;
public ImmutableClass(int i, String s, ComplexObj o){
this.index = i;
this.tStr = s;
ComplexObj cobj = new ComplexObj(o.someVar);
this.cObj = cobj;
}
public static void main(String[] args) {
ImmutableClass icls = new ImmutableClass(5,"Hello World",new ComplexObj(100));
System.out.println(icls.index + " | " + icls.tStr + " | " + icls.cObj.someVar);
icls.cObj.someVar = 5;
System.out.println("Second run :" + icls.index + " | " + icls.tStr + " | " + icls.cObj.someVar);
}
}
And here is the implementation of the ComplexObj
class:
package com.immutable;
public class ComplexObj {
int someVar;
public ComplexObj(int i){
this.someVar = i;
}
}
When I create an instance of ImmutableClass
I am making a deep copy of ComplexObj
in the constructor of ImmutableClass
, however I was able to update the value of cObj
via icls.cObj.someVar
that kind of breaks immutability of the my class. What am I doing wrong here?