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
List implementations of list interface?
Can we write class inside a class in java?
What is the purpose of skeleton and stub?
Can we use switch statement with strings?
Explain about main() method in java ?
Can we define private and protected modifiers for the members in interfaces?
How to create a custom exception?
What is OOP's Terms with explanation?
Write a java program to print fibonacci series?
What is the exact difference in between Unicast and Multicast object?
What is preparedstatement in java?
What is the largest data type in java?
What is the relationship between class and object?
How do you use spaces in java?
Are floats faster than doubles?