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
How many bits is a char?
What is prime number in java?
What happens when a thread cannot acquire a lock on an object in java programming?
Difference between a process and a program?
Is there any tag in htm to upload and download files?
In how many ways we can do synchronization in java?
Is multiple inheritance supported by java?
How are destructors defined in java?
What is early binding and late binding in java?
Give some features of interface?
What is the scope or life time of instance variables?
Give reasons supporting that string is immutable.
What is a newline character in java?
Are arrays dynamic in java?
What is lossy conversion in java?