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
what is ststic with example
Are arrays passed by reference in java?
What is a java developer salary?
What is the difference between size and length in java?
What is the collections api?
How to reverse a string in java?
What is an image buffer?
What is meant by flickering?
What about anonymous inner classes in java?
Can we call virtual funciton in a constructor ?
When a thread is executing synchronized methods , then is it possible to execute other synchronized methods simultaneously by other threads?
What is an escape character in java?
What is an object in java?
Can private members of a base class are inheritable justify?
Why char array is preferred over string for storing password?