jagannath


{ City }
< Country > india
* Profession *
User No # 93700
Total Questions Posted # 0
Total Answers Posted # 1

Total Answers Posted for My Questions # 0
Total Views for My Questions # 0

Users Marked my Answers as Correct # 5
Users Marked my Answers as Wrong # 2
Questions / { jagannath }
Questions Answers Category Views Company eMail




Answers / { jagannath }

Question { TCS, 4323 }

can any one send me the example program of immutable class?


Answer

public class ImmutableClass {
int i;
public ImmutableClass(int i)
{
this.i=i;
}
public int getI()
{
return i;
}
public ImmutableClass setI(int i)
{
if(i==this.i)
{
return this;
}
else
return new ImmutableClass(i);
}
public static void main(String args[])
{
ImmutableClass ic = new ImmutableClass(5);
ic.getI();
System.out.println(ic);
ic = ic.setI(10);
System.out.println(ic);
}
}
// If you pass 5 as the value in setter method, you will see
same address. It means whenever you are trying to change the
value of variable, a new object is created and returned. So
your object is immutable.

Is This Answer Correct ?    5 Yes 2 No