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

Answer Posted / jagannath

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



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How many bits is a char?

533


What is prime number in java?

530


What happens when a thread cannot acquire a lock on an object in java programming?

540


Difference between a process and a program?

611


Is there any tag in htm to upload and download files?

604






In how many ways we can do synchronization in java?

519


Is multiple inheritance supported by java?

502


How are destructors defined in java?

567


What is early binding and late binding in java?

589


Give some features of interface?

580


What is the scope or life time of instance variables?

652


Give reasons supporting that string is immutable.

493


What is a newline character in java?

563


Are arrays dynamic in java?

528


What is lossy conversion in java?

552