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 javac in java?
what is the difference between Object Based Language and Object Oriented Language?
What do you mean by local class?
why we use merge option in hybernate pls give a ex snippet
What is immutability in java?
What is an error in java?
What is the purpose of the return statement?
What is garbage collection? What is the process that is responsible for doing that in java?
What is the core java?
State some advantages of java?
Is arraylist ordered in java?
How can we make a class singleton?
What is codebase?
What are the advantages of functions?
Is main an identifier?