In Java, there are several immutable classes like String, Integer and all wrapper classes.
Immutable objects are the objects which fields can not be modified.
So Immutable class does not have any setter methods.
When we are writing the class that generate immutable objects then we must provide only private and final fields and class should be final.
for example -
public class M {
int m;
public int getM() {
return m;
}
public void setM(int m) {
this.m = m;
}
public String toString() {
return ""+m;
}
}
------------
public final class IM {
final private int x;
final private int y;
final private M z;
IM(int x,int y, M z){
this.x=x;
this.y=y;
this.z=z;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public M getZ() {
return z;
}
public IM addCordinate(IM im){ // like concat() in String
M newM = new M();
newM.setM(this.z.getM()+im.z.getM());
return new IM(this.x+im.x,this.y+im.y, newM);
}
public String toString() {
return "x: "+x+", y: "+y+", z: "+z;
}
}
------------
public class TestImmutability {
public static void main(String[] args) {
M m=new M();
m.setM(3);
IM im=new IM(1,2,m);
System.out.println(im);
M m1=new M();
m1.setM(1);
IM im1 = new IM(3,2,m1); // never share mutable fileds like - new IM(3,2,m) ,m already used
System.out.println(im.addCordinate(im1));// im.addCordinate(im1) returns a new one object.
}
}
for further help - Immutable Objects
Thursday, September 24, 2009
Subscribe to:
Posts (Atom)