Monday, 16 February 2015

Can we create a userdefined immutable class?

     Yes. 
         i)     Make the class as final and
         ii)   make the data members as private and final.

Program:
final class Test{
private int i;
Test(int i){
this.i=i;
}
public Test modify(int i){
if(this.i==i){
return this;
return(new Test(i))
}
}
public static void main(String args[] ){
Test t1= new Test(10);
Test t2= t1.modify(10)
Test t3= new Test(10);
Test t4=t1.modify(100);
System.out.println(t1==t2);    //true
System.out.println(t1==t4);//false
System.out.println(t1==t3)//true
}
}

No comments:

Post a Comment