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
Can a class with private constructor be extended?
What will happen if a thrown exception is not handled?
How many bytes are there?
Explain importance of throws keyword in java?
What is difference between word and integer?
What is string variable?
What is the significance of listiterator?
Can we write class inside a class in java?
Explain Basics of OOP Language in java
What is core java called?
what is a thread pool in java and why is it used?
What is palindrome in java?
Explain about method local inner classes or local inner classes in java?
Can you have two constructors in java?
Explain the meaning of java applet.