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

what is ststic with example

1595


Are arrays passed by reference in java?

486


What is a java developer salary?

544


What is the difference between size and length in java?

513


What is the collections api?

572






How to reverse a string in java?

526


What is an image buffer?

534


What is meant by flickering?

656


What about anonymous inner classes in java?

561


Can we call virtual funciton in a constructor ?

1776


When a thread is executing synchronized methods , then is it possible to execute other synchronized methods simultaneously by other threads?

569


What is an escape character in java?

530


What is an object in java?

557


Can private members of a base class are inheritable justify?

488


Why char array is preferred over string for storing password?

588